c ++从每个单词之间带有':'的文件中读取

c++ reading from file with ':' between each word

如何读取格式的文件:

121:yes:no:334

这是我的代码:

int main(){

    string one, two;
    int three, four;

    ifstream infile;

    infile.open("lol.txt");

    infile >> three;

    getline(infile, one, ':');

    getline(infile, two, ':');

    infile >> four;

    cout << three << one << two << four;
    return 0;
}

输出:121yes0

所以它忽略了 secong get 行,并且以某种方式找到了 0。

文件内容

121:yes:no:334

infile >> three;           it would input 121
getline(infile, one, ':'); it did not take input due to :
getline(infile, two, ':'); it would take yes
infile >> four;            it take none

所以你可以这样做

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

using namespace std;

int main()
{

    string one, two;
    int three, four;

    ifstream infile;

    infile.open("lol.txt");

    infile >> three;

    infile.ignore();

    getline(infile, one, ':');

    getline(infile, two, ':');

    infile >> four;

    cout << three << one << two << four;

    return 0;
}

问题是在第一次读取之后,流看起来像这样

:yes:no:334

所以第一个getline会读取“:”之前的空字符串,第二个会变成红色"yes",最后一个整数提取会失败。

一路使用getline,边走边转换为整数;

int main(){
    string token;
    ifstream infile("lol.txt");
    getline(infile, token, ':');
    int three = std::stoi(token);
    string one;
    getline(infile, one, ':');
    string two;
    getline(infile, two, ':');
    getline(infile, token, ':');
    int four = std::stoi(token);
    cout << three << one << two << four;
    return 0;
}

(错误处理留作练习。)

int main(){
ifstream dataFile;
dataFile.open("file.txt");
int num1, num2;
dataFile >> num1; // read 121
dataFile.ignore(1, ':');
string yes, no;
getline(dataFile, yes, ':'); // read yes
getline(dataFile, no, ':'); // read no
dataFile >> num2; //read 334
return 0;}