因此,我正在編寫一個程序,執行深度優先搜索。是的,這是家庭作業,但我遇到的問題並不是作業的學習點。我被給予格式不正確的輸入,並且無法將輸入分離爲有效變量並將其存儲。當我說格式不正確的數據時,我的意思是,有效數據和每行變量數量之間沒有特定數量的空格是不一致的......試圖找到一種更優雅的方式來獲取我需要的數據,而不是嵌套3個循環。任何幫助是極大的讚賞。 我當前的代碼:輸入C++的解析行
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)
什麼是數據?字符串或int或??? – Tahlil
'operator >>'會爲你跳過所有主要的空白(包括換行符),你只需要關注值是否正確。 – user657267
你想使用從當前行初始化的'std :: istringstream'。 –