'How to save a input string in C++?
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
ofstream wysla;
wysla.open("wysla.txt", ios::app);
int kaput;
string s1,s2;
cout<<"Please select from the List below"<<endl;
cout<<"1.New entry"<<endl;
cout<<"2.View Previous Entries"<<endl;
cout<<"3.Delete an entry"<<endl;
cin>>kaput;
switch (kaput)
{
case 1:
cout<<"Dear diary,"<<endl;
getline(cin,s1);
wysla<<s1;
wysla.close();
break;
}
return 0;
}
In this code I have tried to save a string of characters but it is not possible e.g,.. when I use getline nothing is saved on the text file when I use cin only the first word is saved. I would like to save the whole entry what do I do?
Solution 1:[1]
You might need to insert a cin.ignore() after cin >> kaput to read the newline character at the end of the first input. Otherwise getline sees this newline as the first character, consumes it and ends reading.
Solution 2:[2]
When you enter the number, number will be read into kaput variable, but '\n' character will still be in the buffer, which will be read by getline). To resolve this issue you need to call cin.ignore() to remove newline character from the stdin buffer
Solution 3:[3]
This can work :
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main() {
string firstname;
ofstream name;
name.open("name");
cout<<"Name? "<<endl;
cin>>firstname;
name<<firstname;
name.close();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Werner Henze |
| Solution 2 | Nemanja Boric |
| Solution 3 | Vivek Jain |
