如何从文件中读取整行(带空格)? [英] How to read the whole lines from a file (with spaces)?

查看:395
本文介绍了如何从文件中读取整行(带空格)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用STL。我需要从文本文件中读取行。如何读取行直到第一个 \ n 但是直到第一个''(空格)?

I am using STL. I need to read lines from a text file. How to read lines till the first \n but not till the first ' ' (space)?

例如,我的文本文件包含:

For example, my text file contains:

Hello world
Hey there

如果我这样写:

ifstream file("FileWithGreetings.txt");
string str("");
file >> str;

然后 str 将仅包含Hello但我需要Hello world(直到第一个 \ n )。

then str will contain only "Hello" but I need "Hello world" (till the first \n).

我以为我可以使用方法 getline()但它要求指定要读取的符号数。在我的情况下,我不知道我应该阅读多少个符号。

I thought I could use the method getline() but it demands to specify the number of symbols to be read. In my case, I do not know how many symbols I should read.

推荐答案

你可以使用getline:

You can use getline:

#include <string>
#include <iostream>

int main() {
   std::string line;
   if (getline(std::cin,line)) {
      // line is the whole line
   }
}

这篇关于如何从文件中读取整行(带空格)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆