C ++逐行读取并输出每一行

时间:2012-11-19 21:26:57

标签: c++ io

假设我有一个文本文件,文本文件包含以下内容:

你好世界
欢迎使用C ++

如何从.txt文件中逐行打印?例如,这是我的代码的一部分

while (getline(input, document))
{
    if (!document.empty())
    {
        if (lineisthere(document)) {
            cout << "The word" << // << "is there" << endl;
        } else {
            cout << "The word" << // << "is not there" << endl;
        }
        line++;
    }
}
input.close(); //closes the input

我希望我的输出看起来像这样:

Hello Word 这个词是有的 但是,欢迎使用C ++ 这个词不存在

3 个答案:

答案 0 :(得分:2)

您似乎只想使用document表示//

cout << "The word " << document << " is there" << endl;

答案 1 :(得分:0)

试试这个:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () 
{
  string text;
  ifstream ifs("hello.txt");


    while(!ifs.eof()) 
    {
      getline(ifs,text);
      cout << "" << text << "\n" ;
    }

  return 0;
}

答案 2 :(得分:0)

此代码正在逐行打印文本文件:

    #include<iostream>
#include<fstream>
#include<cstdlib>
#include<iomanip>
using namespace std;
int main()
{
string filename;
ifstream file;
    cout<<"enter file name";
    getline(cin,filename);
     filename.append(".txt");
    file.open(filename.c_str());


    string text;
    while(getline(file,text))
    {
        cout<<text<<endl;
    }
file.close();

    return 0;
}
相关问题