【发布时间】:2014-04-17 08:03:38
【问题描述】:
我正在编写一个执行深度优先搜索的程序。是的,这是家庭作业,但我遇到的问题不是作业的学习点。我收到格式错误的输入,并且无法将输入分离为有效变量并存储它们。当我说格式错误的数据时,我的意思是有效数据之间没有特定数量的空格,并且每行的变量数不一致......试图找到一种更优雅的方式来获取我需要的数据而不是嵌套3个循环。任何帮助是极大的赞赏。 我当前的代码:
int main()
{
//read in first line (# of lines WITH data)
cout << "enter the number of lines\n";
cin >> lines;
//if non integer entered it won't error now
while(!cin)
{
cin.clear(); // clears the error flags
cin.ignore(20, '\n'); //flush the buffer
cout <<"\ndid not enter a valid integer, please try again\n\n";
//reprompt for VALID input
cout << "enter the number of lines\n";
cin >> lines;
}
//lines should now have a valid int input value
//eat blank line
getline(cin,str);
//read in (# of lines WITH data retrieved from first input)
for(int i = 0; i < lines; i++)
{
getline(cin, str);// read first string
//process str
//while not end of line
//{
//breakup line into individual variables
std::string delim = " "; //set space as a delimiter
size_t pos = 0;
string token;
while ((pos = str.find(delim)) != std::string::npos)
{
token = str.substr(0,pos);
//set token to variable that increases (array location?)
//get char, loop to check if chare = " ", eat it if it is until its not
}
//}
//place variables in array location
//...
}
//eat blank line at end of data set
getline(cin,str);
//alphabetize array
// ...
return 0;
}
样本输入:
11
Harry Kate(18) Fred(5) Carol(6)
Alice James(25) Daisy(21) Kate(10)
Carol Fred(2) Harry(6) Daisy(12)
Ivy James(16) Bob(24)
Daisy Carol(12) Alice(21) Elvis(28)
Elvis James(18) Daisy(28) Fred(29)
Kate Alice(10) Fred(14) Harry(18) Gerald(20)
Fred Kate(14) Carol(2) Harry(5) Elvis(29)
Gerald Kate(20) Bob(17) James(10)
James Gerald(10) Elvis(18) Alice(25) Ivy(16)
Bob Ivy(24) Gerald(17)
【问题讨论】:
-
数据是什么?字符串或整数或???
-
operator>>将为您跳过所有前导空格(包括换行符),您只需关注值是否正确。 -
你想使用从当前行初始化的
std::istringstream。 -
为什么不给我们一个有代表性的实际输入部分以与您的代码交叉引用?
-
实际样本输入:11 Harry Kate(18) Fred(5) Carol(6) Alice James(25) Daisy(21) Kate(10) Carol Fred(2) Harry(6) Daisy( 12) Ivy James(16) Bob(24) Daisy Carol(12) Alice(21) Elvis(28) Elvis James(18) Daisy(28) Fred(29) Kate Alice(10) Fred(14) Harry(18)杰拉德(20) 弗雷德凯特(14) 卡罗尔(2) 哈利(5) 猫王(29) 杰拉德凯特(20) 鲍勃(17) 詹姆斯(10) 詹姆斯杰拉德(10) 猫王(18) 爱丽丝(25) 艾薇(16) ) 鲍勃·艾维(24) 杰拉德(17)