2017-11-04 91 views
0

这是我的代码,我附上了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

谢谢。

+0

你的第一个错误是不发布[最小,完整和可验证的例子](https://stackoverflow.com/help/mcve) 。 –

回答

1

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

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


(一)好,直到它环绕(如果它环绕)。但是,这将是一个可怕很多你需要输入的逗号:-)

+0

你是否建议逗号昏迷? – user4581301

相关问题