C++ 为什么程序抱怨逗号太多?

C++ 为什么程序抱怨逗号太多?,c++,C++,这是我的代码,我附上了Zybooks期望的输出以及我的输出的屏幕截图。我试图让它准确地输出Zybooks所要求的内容,但似乎有些地方出了问题。不过它正在编译。或者是因为书太傻了 #include <iostream> #include <string> #include <vector> #include <sstream> #include <iomanip> #include <cstring> using names

这是我的代码,我附上了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;
}
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
字符串标题;
字符串col1;
字符串col2;
字符串val;
int numCommas=0;
矢量数据;
矢量数据;

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

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



(a) 好的,直到它结束(如果它结束)。但是你需要输入大量逗号:-)

你的第一个错误是没有发布一个。你是建议使用逗号吗?