简体   繁体   English

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

[英]Why does program complain of too many commas?

Here is my code, I have attached the screenshot of what output Zybooks expects, and what my output is. 这是我的代码,我附上了Zybooks预期输出以及输出内容的屏幕截图。 I am trying to get it to output exactly what Zybooks is asking, however something seams to be wrong. 我试图使它输出的正是Zybooks的要求,但是似乎有些错误。 It is compiling though. 它正在编译。 Or maybe Zybooks is just being stupid? 还是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;
}

Thanks. 谢谢。

在此处输入图片说明

Thanks. 谢谢。

Your problem is that you initialise numCommas to zero at the start of the program rather than at the start of each author input. 您的问题是,您在程序开始numCommas不是在每个作者输入开始时将numCommas初始化为零。 That means, once it exceeds one, it will stay that high at least (a) , meaning future inputs will always be seen as having too many commas. 这意味着,一旦超过一个,它将至少保持在(a)的高位,这意味着将来的输入将始终被视为具有太多逗号。

You just need to set it to zero immediately before checking each input. 您只需要在检查每个输入之前立即将其设置为零即可。


(a) Well, until it wraps around (if it wraps around). (a)好,直到它环绕(如果它环绕)。 But that will be an awful lot of commas you need to input :-) 但是,这将是一个可怕的很多,你需要输入逗号:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM