保存到文件时,会忽略空白后的单词

when saving to file, words after white space are ignored

本文关键字:空白 单词 存到文件      更新时间:2023-10-16

我一直在努力保存到文件中,结果就是这样。唯一的问题是,空格后的任何内容都会被忽略(如果你键入"johnsmith"(,它会打印出来("最后一个使用这个文件的人是:john"(我使用GNUGCC编译器的代码块。这是代码:

    #include <iostream>
    #include <cstdlib>
    #include <fstream>
    using namespace std;
    int main()
    {
        string name;
        ofstream saveData;
        ifstream Data;
        Data.open("Info.data", ios::binary);
        Data >> name;
        Data.close();
        cout << "The last person to use the file was " << name << endl;
        cout << "What is your name?" << endl;
        cin >> name;
       saveData.open("Info.data", ios::binary);
       saveData << name;
       cout << name << endl;
       system("PAUSE");
       saveData.close();
       return 0;
   }

感谢

对于字符串,ifstream(包括cin(的对象从开始到第一个空格使用输入,空格为space、TAB和NELINE。因此,您应该使用getline而不是cin >>

试试这个:

Data.open("Info.data");
getline(Data, name);
Data.close();

cout << "What is your name?" << endl;
//cin >> name;
getline(cin, name);

更新:

顺便说一下,在你的代码中之后

   Data.open("Info.data", ios::binary);

你使用

   Data >> name;

所以,以二进制模式打开的流被>>读取——这不是很好。