c++ - C++ 读写文件

标签 c++ string file-io while-loop

<分区>

我设法写入了文本文件,但我读取的文件出了点​​问题。这是我的代码:

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

using namespace std;

int main()
{
    string line, s;
    ofstream out_file;
    out_file.open("hello.txt");
    for(int count = 0; count< 5; count++)
    {
        out_file << "Hello, World" << endl;
    }
    out_file.close();

    ifstream in_file;
    in_file.open("hello.txt");
    if (in_file.fail())
    {
        cout << "File opening error. " << endl;
    }
    else
    {
        while(getline(in_file,line))
        {
            in_file >> s;
            cout << s << endl;
        }
    }
    in_file.close();

    system("Pause");
    return 0;
}

我设法将 5 次“Hello, World”写入一个文本文件。然而,当程序运行时,它只打印了 4 次“Hello”,并在第 5 行打印了“World”。从我的代码来看,它不是应该打印 5 次“Hello, World”吗?有人可以指出错误在哪里吗?

最佳答案

  while(getline(in_file,line))
{
    in_file >> s;
    cout << s << endl;
}

应该是:

while(getline(in_file,line))
{
    cout <<line<< endl;
}

因为您从文件中读取到 line,而不是 s。所以你应该在 line 中打印内容。

关于c++ - C++ 读写文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16792708/

相关文章:

c++ - 运算符重载和复制构造函数 - C++

sql - Postgres : Select the maximum integer substring of a column value

关于字符串操作的 Java 问题 - 反转文本将 "null"添加到末尾

c# - 标记为内容的 Windows Phone 8 文件的位置

java - 我可以使用什么文件格式直接从程序输出格式化的文本文件,而无需标记太复杂?

c++ - 使用整数的最佳方法?

c++ - 在 C++ 中设置构造函数默认值

c++ - 你如何在 C++ 中四舍五入小数位?

java - 自定义 'String' 类

node.js - Node js中如何处理文件读写?