如何在C ++中从fstream中读取两个单词,然后读取一行?

问题描述 投票:-1回答:1

我用C ++编码时遇到了一个问题。我有一个输入(fstream将要读取的文件):

1 2
three four five six

我要用此输入执行的操作是:取第一行,并将其拆分为两个string变量:一个为1,另一个为2。之后,对于下一行,我想使用某种形式getline()的整数可能会得到“三四五六”作为string。我目前已经尝试过:我有一些代码声明了三个字符串变量:

#include<string>
// Main function...
string str1, str2, str3;
fstream inf;
inf.open('somefile.txt');
inf >> str1 >> str2 >> str3;
inf.close();

此代码正确地采用了“ 1”和“ 2”,但仅采用了下一行的第一个字符。我在这里错了吗?

任何帮助将不胜感激。谢谢!

c++ string fstream
1个回答
0
投票

忽略使用std::getline()\n来获得整行为字符串,然后使用ignore(),如下所示

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

int main(){
    std::string str1, str2, str3;
    std::fstream inf;
    inf.open("somefile.txt");
    inf >> str1 >> str2;
    inf.ignore();
    std::getline(inf, str3);
    inf.close();

    //Displying them
    std::cout<<str1<<" "<<str2<<" "<<str3;
    }
© www.soinside.com 2019 - 2024. All rights reserved.