gpt4 book ai didi

c++ - 输入c++的解析行

转载 作者:行者123 更新时间:2023-11-28 02:50:42 24 4
gpt4 key购买 nike

我正在编写一个执行深度优先搜索的程序。是的,这是家庭作业,但我遇到问题的部分不是作业的学习点。我收到格式错误的输入,无法将输入分成有效变量并存储它们。当我说格式错误的数据时,我的意思是有效数据之间没有特定数量的空格,每行变量的数量不一致......试图找到一种更优雅的方式来获取我需要的数据而不是嵌套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)

最佳答案

您可以使用 std::istringstream 和 std::istream_iterator 标记每一行。下面给出了示例代码。

#include <iostream>
#include <iterator>
#include <vector>
#include <string>
#include <sstream>

template <typename T>
std::vector<T> parse_line(const std::string& s) {
std::vector<T> result;
std::istringstream iss(s);
std::copy(std::istream_iterator<T>(iss), std::istream_iterator<T>(),
std::back_inserter(result));
return result;
}

int main() {
std::string s{"Harry Kate(18) Fred(5) Carol(6)"};
auto r = parse_line<std::string>(s);
for (auto const& e : r) std::cout << e << std::endl;
return 0;
}

关于c++ - 输入c++的解析行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23127765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com