[英]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;
}
output: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;
}
问题是第一次读取后,stream 看起来像这样
:yes:no:334
所以第一个getline
会读取“:”之前的空字符串,第二个会读取红色的“yes”,最后一个integer提取会失败。
一直使用getline
并像 go 一样转换为整数;
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;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.