c++ - 如何从文件中只读取一行

标签 c++ visual-c++ c++11

我尝试读取文件的第一行,但是当我尝试输入保存在文件中的文本时,它会打印出整个文件,而不仅仅是一行。该工具也处理中断或空格。

我使用以下代码:

//Vocabel.dat wird eingelesen
ifstream f;                         // Datei-Handle
string s;

f.open("Vocabeln.dat", ios::in);    // Öffne Datei aus Parameter
while (!f.eof())                    // Solange noch Daten vorliegen
{
    getline(f, s);                  // Lese eine Zeile
    cout << s;
}

f.close();                          // Datei wieder schließen
getchar();

最佳答案

摆脱 while 循环。替换这个:

  while (!f.eof())                    // Solange noch Daten vorliegen
  {
    getline(f, s);                  // Lese eine Zeile
    cout << s;
  }

机智:

  if(getline(f, s))
    cout << s;


编辑:响应新要求“它读取我可以在第二个变量中定义的行?”

为此,您需要循环,依次读取每一行,直到读完您关心的行:

// int the_line_I_care_about;  // holds the line number you are searching for
int current_line = 0;          // 0-based. First line is "0", second is "1", etc.
while( std::getline(f,s) )     // NEVER say 'f.eof()' as a loop condition
{
  if(current_line == the_line_I_care_about) {
    // We have reached our target line
    std::cout << s;            // Display the target line
    break;                     // Exit loop so we only print ONE line, not many
  }
  current_line++;              // We haven't found our line yet, so repeat.
}

关于c++ - 如何从文件中只读取一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11140566/

相关文章:

c++ - 合并 unique_ptr 的两个 vector 时“使用已删除的函数”

c++ - 跨平台 C++ 动态库插件加载器

c++ - 从相同类型的两个对象比较数据成员的最简单方法

c++ - 取消链接不删除文件

c++ - 我无法使用 VS2010 运行 openCV2.3.1,因为找不到 opencv_core231d.dll

http - 如何获取HTTPS网页?

c++ - 将指向局部变量的指针传递给另一个进程有时有效,但有时无效

c++ - 为什么协程的返回类型必须是可移动构造的?

c++ - 在类的私有(private)部分中为复制构造函数定义原型(prototype)如何防止类的复制?

c++ - 检测CSV分隔符是 ";"还是 ","