【问题标题】:when saving to file, words after white space are ignored [duplicate]保存到文件时,空格后的单词被忽略[重复]
【发布时间】:2016-08-06 06:05:33
【问题描述】:

我一直在努力保存到文件,这就是结果。唯一的问题是空格后的任何内容都会被忽略,(如果您输入“john smith”)它会打印 (“最后一个使用这个文件的人是:john”)我正在使用带有 GNU GCC 编译器的代码块。代码如下:

    #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;
   }

谢谢

【问题讨论】:

    标签: c++


    【解决方案1】:

    对于ifstream(包括cin)的字符串对象,输入从开始到第一个空格,空格是SPACE、TAB和NELINE。 所以,你应该使用getline 而不是cin &gt;&gt;

    试试这个:

    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;
    

    所以,&gt;&gt; 读取以二进制模式打开的流 - 这不太好。

    【讨论】:

    • 建议将 istream 替换为 ifstream,将空格替换为空格。
    • getline 在哪个#include 文件中?
    • getline(name);不适用于#include
    • @JakeWickham 小心混合 >> 和 getline。 >> 在空白处停止,但不会从流中提取它。 Stackoverflow 中充斥着人们对 getline 返回空字符串感到困惑的问题,因为在用户输入输入并按 Enter 后,流中留下了行尾。
    • 通常的建议是不要将getline() 和运营商&gt;&gt; 混合在同一个流上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2014-02-16
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    相关资源
    最近更新 更多