【问题标题】:C++ read file only gives first word [duplicate]C ++读取文件仅给出第一个单词[重复]
【发布时间】:2014-08-03 02:01:11
【问题描述】:

我知道我不应该在这个范围内使用命名空间 std (using namespace std) 作为全局,但对于这个例子,我会的。

我最理想的是将文本保存到 .txt 文件并检索它。我知道 best 选项是fstream,所以我决定使用它。

下面的代码打印出“This”。为什么打印的是“This”而不是全文?

代码如下:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    ifstream fin;
    ofstream fout;
    string text;

    fout.open("C++_text_file_test.txt");
    fout << "This is basic text";
    fout.close();

    fin.open("C++_text_file_test.txt");
    fin >> text;
    fin.close();

    cout << text << endl;
    cin.get(); // waits for user to press enter 

    return 0;
}

我尝试研究但不太了解使用循环的过程。有没有更简单的方法或者有人可以解释一下吗?

【问题讨论】:

    标签: c++ fstream


    【解决方案1】:

    &gt;&gt; 运算符在用于提取字符串时,仅抓取第一个空白字符之前的字符。尝试使用getline 获取整行。

    【讨论】:

      猜你喜欢
      • 2012-03-17
      • 2021-05-24
      • 1970-01-01
      • 2019-02-11
      • 2020-07-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多