[英]Why Doesn't My Program Work Correctly
我的程序需要解析一個csv文件,並確定缺少的數字組合。 順序無關緊要。
該程序會編譯並運行,但會打印出文件中已打印在一行中的數字。
輸入(mega2.csv):
123
134
142
注意234
不在列表中。
預期輸出:該程序應該輸出234
因為它是唯一未使用的組合。 相反,沒有任何輸出。
碼:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
int main()
{
ifstream inFile;
string value;
string fileName;
int count;
int amount, playCount;
int a,b,c,d,e,f,g,h,i,j,k,l;
srand(time(0));
char ch;
do{
cout << "Enter number of plays (or -number to quit): ";
cin >> amount;
cout << endl;
playCount = 1;
while( playCount <= amount ){
do{
inFile.open("mega2.csv");
//create random numbers a,b,c,d,e,f= mega num < 10
a = rand() % 5;
if(a == 0){a = 1;}
do{
b = rand() % 5;
if(b == 0){b = 1;}
}while(b == a);
do{
c = rand() % 5;
if(c == 0){c = 1;}
}while(c == a || c == b);
//Load numbers into g,h,i,j,k,l
do{
inFile >> g;
inFile.get(ch);
inFile >> h;
inFile.get(ch);
inFile >> i;
inFile.get(ch);
int count = 0;
cout << g << "," << h << "," << i << endl;
//A
if( a == g || a == h || a == i ){
count++;
}
//B
if( b == g || b == h || b == i ){
count++;
}
//C
if( c == g || c == h || c == i ){
count++;
}
}// close second half do loop
while(inFile && count < 3);
inFile.close();
inFile.clear();
} // close whole do loop
while(count >= 3);
cout << endl;
cout << endl;
cout << endl;
cout << a << "," << b << "," << c << endl;
cout << endl;
playCount++;
} // End playCount while loop
}// End main do loop
while(amount >= 0); // quit program with negative number
system("pause");
return 0;
}
int count;
main()
中的從未被初始化,因此它包含不確定的值。
首先初始化它:
int count = 0;
編輯:
對於那些晚到聚會的人或那些匆忙投票但又不想真正閱讀代碼的人:
這里有兩個count
變量。 一個在main()
范圍內,另一個在do-while
循環內。 循環內的count
已初始化,但main()
的count
未初始化,並且這是在do-while
條件下使用的count
。
這是一個小片段 ,它演示了如果有人仍然難以理解這一點,我在說什么。
您使用rand()
檢測缺失組合的算法看起來非常可疑。 但是我想這是某種練習,所以我會讓您自己解決這個問題。
您需要使用代碼來解決一些問題,這將導致您所看到的令人困惑的行為。
您的變量中只有一個被初始化。 他們都應該被初始化,如下所示:
string fileName = "mega2.csv";
您有兩個名為count
變量。 您應該重命名它們(以及其他命名錯誤的變量)。 他們在計數什么?
您無需檢查文件是否已成功打開,否則不能采取適當的措施:
if (!inFile) { std::cerr << "Could not open file [" << fileName << "]. Exiting." << std::endl; break; }
您不會檢查變量是否已成功從文件中讀取,如果沒有,則應采取適當的措施。 鑒於您正嘗試從文件中讀取三個逗號分隔的值,但您的輸入文件不包含任何逗號,因此這可能是一個問題!
您不驗證用戶輸入。
cout << "Enter number of plays (or -number to quit): "; if (!(cin >> amount)) { std::cerr << "Invalid input" << std::endl; break; }
您有未使用的變量。 刪除這些。
另外,您的main()
做得太多。 嘗試將您的代碼分解成很多非常小的組件。 這將使您更易於測試和他人閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.