gpt4 book ai didi

c++ - 为什么程序提示逗号太多?

转载 作者:行者123 更新时间:2023-11-28 04:56:01 26 4
gpt4 key购买 nike

这是我的代码,我附上了 Zybooks 期望输出的屏幕截图,以及我的输出是什么。我试图让它准确输出 Zybooks 所要求的内容,但似乎有些地方出错了。它正在编译。或者也许 Zybooks 只是愚蠢?

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include <cstring>

using namespace std;

int main() {

string title;
string col1;
string col2;
string val;
int numCommas = 0;
vector<string> stringData;
vector<int> intData;

cout << "Enter a title for the data:" << endl;
getline(cin, title);
cout << "You entered: " << title << endl << endl;

cout << "Enter the column 1 header:" << endl;
getline(cin, col1);
cout << "You entered: " << col1 << endl << endl;

cout << "Enter the column 2 header:" << endl;
getline(cin, col2);
cout << "You entered: " << col2 << endl << endl;

while (1) {
cout << "Enter a data point (-1 to stop input):" << endl;
getline(cin, val);

if (val == "-1") {
break;
}

if (val.find(',') == -1) {
cout << "Error: No comma in string." << endl << endl;
}
else {
for (int i = 0; i < val.length(); i++) {
if (val.at(i) == ',') {
numCommas++;
if (numCommas > 1){
break;
}
}
}

if (numCommas == 1) {
stringData.push_back(val.substr(0, val.find(',')));
intData.push_back(stoi(val.substr(val.find(',') + 1, val.length() - 1)));
cout << "Data string: " << val.substr(0, val.find(',')) << endl;
cout << "Data integer: " << stoi(val.substr(val.find(',') + 1, val.length() - 1)) << endl;
}
else {
cout << "Error: Too many commas in input." << endl << endl;
}
}
}

return 0;
}

谢谢。

enter image description here

谢谢。

最佳答案

您的问题是您在程序开始时将 numCommas 初始化为零,而不是在每个作者输入的开始时。这意味着,一旦它超过 1,它将至少保持在那个高度(a),这意味着 future 的输入将始终被视为包含太多逗号。

您只需在检查每个 输入之前立即将其设置为零。


(a) 好吧,直到它环绕(如果它环绕)。但是你需要输入很多逗号 很糟糕 :-)

关于c++ - 为什么程序提示逗号太多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47107474/

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