在代码中定义字符串与控制台输入之间的区别
Difference between defining string in-code vs. console input
我正在为一个数据结构类做项目。目标是用一棵树来计算隐喻性侏儒是否可以用隐喻性钻石支付隐喻性税款。输入以字符串的形式给出,格式为"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问题的方式。让事情变得简单多了,你不同意吗?:)
相关文章:
- 我的 c++ 程序似乎没有发现字符串和我拥有但输入使用 getline 的变量之间的比较
- 将线程之间的标准输入/输出重定向
- 计算当前日期和用户输入日期问题之间的天数
- 在C++代码中,如何让用户在2个文本字符串之间输入一个数字
- 在 c++ 中反转数组时,为什么在输入和输出之间得到一个"random"数字?
- ios_base::sync_with_stdio(false) 在来自标准输入的两个输入之间不起作用
- 我正在尝试创建一个程序,用户在其中输入一系列数字,并且我想列出范围之间的质数
- 我们可以在两个输入之间获得时间吗?
- ios::app 和用于输入的 fstream 之间的交互
- 我们应该使用哪种数据类型来输入一个介于 0<= 数字 <= 10^18 之间的数字
- 在两个输入c++之间花费时间
- 如何让我的程序分开而不是将输入之间的空格计算为整数
- 为什么我的代码要求"请输入 2-12 之间的数字:"两次?
- 在输入和输出之间使用不同数量的样本对音频ffmpegc++进行编码
- 在这个输入中,float和double之间的区别是什么
- 在代码中定义字符串与控制台输入之间的区别
- <</>>运算符重载和输入/输出函数之间的区别
- c++计算输入和保存点的结构与原点之间的距离,根据距离打印出列表
- 使用忽略等输入之间的差异
- 创建一个算法,要求用户输入两个正数,将它们称为 "first" 和 "last" ,并打印第一个正数之间的所有数字的总和