Good day! I was wondering why my program (Written in C++11) keeps cutting off the first character of every user input. Here is my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ofstream dataFile;
dataFile.open("studentData.txt");
string set1, set2, set3, set4;
cout << "How long was the fish when you first measured it?" << endl;
cin.ignore();
getline(cin, set1);
dataFile << set1 << endl;
cout << "How long is the fish now?" << endl;
cin.ignore();
getline(cin, set2);
dataFile << set2 << endl;
cout << "Where was the fish when you first tagged it?" << endl;
cin.ignore();
getline(cin, set3);
dataFile << set3 << endl;
cout << "Where is the fish now?" << endl;
cin.ignore();
getline(cin, set4);
dataFile << set4 << endl;
dataFile.close();
return 0;
}
Here is the output if the input is as follows: set1 - 12 inches set2 - 24 inches set3 - Valdosta, Georgia set4 - Miami, Florida
2 inches
4 inches
aldosta, Georgia
iami, Florida
Why is this happening? I've read up on using cin.ignore and cin.getline, however, I am unable to find a proper solution. Is it my syntax? Am I improperly using the functions? Please bear in mind I am a beginner to programming in C++! ^^
-- Thanks!
Remove the calls to cin.ignore()
, because it's ignoring your first character. The following code worked for me.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ofstream dataFile;
dataFile.open("studentData.txt");
string set1, set2, set3, set4;
cout << "How long was the fish when you first measured it?" << endl;
getline(cin, set1);
dataFile << set1 << endl;
cout << "How long is the fish now?" << endl;
getline(cin, set2);
dataFile << set2 << endl;
cout << "Where was the fish when you first tagged it?" << endl;
getline(cin, set3);
dataFile << set3 << endl;
cout << "Where is the fish now?" << endl;
getline(cin, set4);
dataFile << set4 << endl;
dataFile.close();
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.