我已经开始在类似 hackerrank/hackerearth 的网站上工作。在那里我发现了一个获取输入的问题。在 Java 中很容易。
考虑一个非常简单的读取输入并显示它的问题: 流程就像:
read A
repeat A times
read X1,N1,X2,N2 ; where Xi is any string, Ni is any integer.
display X1+X2, N1+N2
我不知道如何读取 X1、N1、X2、N2,其中 X1 和 X2 是字符串,我也尝试过,但问题是当我读取第一个字符串时它会读取整行,例如当我读取字符串时应该是 X1 但它是 X1,N1,X2,N2。我使用的代码是
scanf("%s,%d,%s,%d", x1, &n1, x2, &n2)
提前致谢,抱歉我的英语不好。
更新#1:
示例行:
3
some,123,thing,456
something,579
a,1,b,2
ab,3
hello,100,world,100
helloworld,200
最佳答案
我认为您正在寻找这样的东西:
int number_of_inputs;
std::cin >> number_of_inputs;
for (int iteration = 0; iteration < number_of_inputs; ++iteration){
int integer1, integer2;
string string1, string2, stupid_comma;
std::cin >> string1 >> stupid_comma >> integer1 >> stupid_comma >> string2 >> stupid_comma >> integer2;
std::cout << string1 << " + " << string2 << " = " << integer1+integer2 << std::endl;
}
edit2:op 提供输入后,我的代码不正确。检查这个答案:Parsing a comma-delimited std::string
edit3:可选的拆分方法 op 要求:
std::vector<std::string> split(const std::string &text, char sep, int num)
{
std::vector<std::string> tokens;
std::size_t start = 0, end = 0;
int elements = 0;
while ((end = text.find(sep, start)) != std::string::npos) {
if ( elements == num) break;
tokens.push_back(text.substr(start, end - start));
start = end + 1;
elements++;
}
tokens.push_back(text.substr(start));
return tokens;
}
edit4:使用拆分功能的新代码:
int number_of_inputs;
std::cin >> number_of_inputs;
for (int iteration = 0; iteration < number_of_inputs; ++iteration){
std:string line;
cin >> line;
int integer1, integer2;
string string1, string2, stupid_comma;
std::vector<std::string> my_line = split(line, ',', 4);
string1 = my_line[0];
string2 = my_line[2];
integer1 = stoll(my_line[1], nullptr, 10);
integer2 = stoll(my_line[3], nullptr, 10);
std::cout << string1 << " + " << string2 << " = " << integer1+integer2 << std::endl;
}
关于c++ - 如何阅读此类输入? A,1,BC,2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43202631/