用逗号分隔流成struct [英] comma separated stream into struct
问题描述
ex data:7,john doe,123-456-7891 123 false st。
我想这样做,我的程序将抓住第一个数字,并将其放在int中,找到逗号,并将第二个数字放在结构的字符串等。
第一个问题是我应该使用类吗?我已经看到了 getline(stream,myString,',');
但是我的参数是不同的数据类型,所以我不能把它们全部放到一个向量中。 p>
我的代码:
struct Person {
int id; //不在乎这是否唯一
字符串名称;
字符串extraInfo;
};
$ b int main(int argc,char * argv []){
assert(argc == 2&&无效的命令行参数数量);
ifstream inputFile(argv [1]);
assert(inputFile.is_open()&&无法打开文件);
$ b 存储这些信息并从一个文件中检索的最好方法是什么是前两个逗号分隔,并以换行符结束?我也希望程序忽略文件中的空行。
解决方案我会逐行读取文件正常 getline()
。然后把它放到一个 stringstream
中以便进一步解析或者使用 string 的 find()
$ b
$ b
Person
,那么答案是没关系。a,b
不能被逗号分隔。确保你有测试,断言所需的功能。I have a structure with an int and two strings. When reading in the file it is comma seperated for the first two values and the last value is terminated by a newline. The third argument could be empty however.
ex data: 7, john doe, 123-456-7891 123 fake st.
I want to make it so that my program will grab the first number and put it in the int, find the comma and put the second number in the struct's string etc.
First question is should I use a class instead? I have seen the getline(stream, myString, ',');
but my arguments are different data types so I can't just throw them all into a vector.
my code:
struct Person{
int id;//dont care if this is unique
string name;
string extraInfo;
};
int main(int argc, char* argv[]){
assert( argc ==2 && "Invalid number of command line arguments");
ifstream inputFile (argv[1]);
assert( inputFile.is_open() && "Unable to open file");
}
What is the best way of storing this information and retrieving it from a file that is comma separated for the first two and ends with a newline? I also want the program to ignore blank lines in the file.
I'd read the file line-by-line using normal getline()
. Then, put it into a stringstream
for further parsing or use string
's find()
functions to split the text manually.
Some more notes:
- I don't understand your first question about using a class. If you mean for
Person
, then the answer is that it doesn't matter. - Using assert for something you don't have control over is wrong, like argc. This should only be used to verify that you didn't make a programming error. Also, if you #define NDEBUG, the asserts are all gone, so they shouldn't really be part of your program logic. Throw std::runtime_error("failed to open file") instead.
- You probably don't want the double quotes in your strings. Also, you might want
"a,b"
to not be split by the comma. Make sure you have tests that assert the required functionality.
这篇关于用逗号分隔流成struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!