在代码中定义字符串与控制台输入之间的区别

Difference between defining string in-code vs. console input

本文关键字:输入 之间 区别 控制台 代码 定义 字符串      更新时间:2023-10-16

我正在为一个数据结构类做项目。目标是用一棵树来计算隐喻性侏儒是否可以用隐喻性钻石支付隐喻性税款。输入以字符串的形式给出,格式为"3 1 2 3 1 2 2 3",这意味着价值为1 2 3的3颗钻石和价值为1 3的3税成本。

我遇到的问题并不是源于树的实现,而是处理将输入解析为可以将其插入树的方式,特别是:当我在测试时直接在代码中输入值时,它会给出正确的输出,但当使用cin时,输出会遇到一些问题。

带有以下代码:

string str;
str = "5 1 2 3 4 5 5 1 2 3 4 5";

str.erase(remove_if(str.begin(), str.end(), ::isspace), str.end());
char ch[str.size()];
strcpy(ch, str.c_str());
int numDiamonds = ch[0] - '0';
cout<<numDiamonds<<" diamonds"<<endl;
int counter = 1;
for(int i = 1; i < numDiamonds+1; ++i){
    int out = ch[i] - '0';
    cout<<out;
    cout<<" ";
    ++counter;
}
cout<<endl;
int numTaxes = ch[numDiamonds+1] - '0';
cout<<numTaxes<<" taxes"<<endl;
for(int i = counter+1; i < str.size(); ++i){
    int out = ch[i] - '0';
    cout<<out;
    cout<<" ";
}
cout<<endl;
}

我的输出看起来是正确的,如下所示:

5 diamonds
1 2 3 4 5
5 taxes
1 2 3 4 5

但当我将"str=5 1…"更改为"cin>>str"时,我的输出看起来很混乱,如下所示。

5 diamonds
-48 -48 -48 -48 -48
-20 taxes
1 diamonds
-48
-48 taxes
2 diamonds
-48 -48
-48 taxes
3 diamonds
-48 -48 -48
-48 taxes
4 diamonds
-48 -48 -48 -48
-48 taxes
5 diamonds
-48 -48 -48 -48 -48
-20 taxes
5 diamonds
-48 -48 -48 -48 -48
-20 taxes
1 diamonds
-48
-48 taxes
2 diamonds
-48 -48
-48 taxes
3 diamonds
-48 -48 -48
-48 taxes
4 diamonds
-48 -48 -48 -48
-48 taxes
5 diamonds
-48 -48 -48 -48 -48
-20 taxes

再多的谷歌搜索也无法解决我的问题,所以我求助于你们。有没有解释为什么cin到字符串中的行为与在代码中定义字符串不同?

谢谢!

这是因为输入在遇到空格时结束,即只读取第一个数字。请改用cin.getline()

确切的输入行应该是:getline(cin, str),因为您使用的是std::string,否则cin.getline()也会完成这项工作。

尝试使用std::getline(cin,str)。

cin只占用下一个空白字符。

您可以使用cin.getline,但一个更好的选择,看看您使用它的目的,是为每个整数循环一个cin

所以你可以做:

vector<int> input;
int x;
while (cin.good()) {
    cin >> x;
    input.push_back(x);
}

cin.good()只是检查流是否仍然。。。嗯,很好。如果流出现问题(例如,如果您到达流的末尾),它将返回0。如果您知道stdin的格式,那么这是从stdin中检索项的好方法,通常情况下,这也是从stdin读取ICPC/toporder问题的方式。让事情变得简单多了,你不同意吗?:)

相关文章: