2011-09-21 57 views
0

我的程序的要点是将数字1 - 1,000,000写入文本文件,生成一个介于1和1,000,000之间的随机数字,在文本文件中搜索该行,取其值并将其平方(这只是一个为我锻炼,它没有实际应用)。问题是,每当我运行它时,值都保持不变,但rand()函数被time(0)接种。我怀疑它是垃圾值,但我不知道它来自哪里(我没有使用GDB或任何其他独立调试器的经验)。下面是我的源代码:程序总是产生相同的值?

#include <fstream> 
#include <ctime> 
#include <iostream> 
#include <string> 
#include <cstdlib> 
using namespace std; 

int main(int argc, char** argv){ 
    ofstream file("log.txt", ios::app); 
    ofstream programLog("programlog.dat", ios::app); 
    cout << "Test Start" << endl; 
    programLog << "Test Start" << endl; 
    cout << "Log file created" << endl; 
    programLog << "Log file created" << endl; 
    ifstream readFile("log.txt"); 
    int foundNum; 
    std::string line = ""; 
    unsigned int loopCount = 1000000; 
    unsigned int numToSearch; 
    const unsigned short min = 1; 
    const int max = 1000000; 
    unsigned int randomLine = 0; 

    for(int i = 0; i <= loopCount; i++){ 
     file << i << endl; 
    } 

    //select random line 
    srand((unsigned)time(0)); 

    while(!(randomLine > min) && !(randomLine < max)){ 
     randomLine = (unsigned)rand(); 
     programLog << randomLine; 
     int newlines = 0; 
     //size_t found; 
     while(getline(readFile, line)){ 
      if(line.find("\n") != string::npos) 
       newlines++; 
      if(newlines == randomLine) 
       numToSearch = atoi(line.c_str()); 
     } 

    } 

    programLog << "Random line selected" << endl; 

    //read line 
    while(std::getline(readFile,line)){ 
     if(atoi(line.c_str()) == numToSearch){ 
      foundNum = numToSearch; 
      break; 
     } 
     else 
      continue; 
    } 

    //square it 
    const unsigned int squared = foundNum*foundNum; 

    programLog << squared; 
    readFile.close(); //end read 
    file.close(); //end log 
    programLog.close(); //end programlog 
    return 0; 
} 
+1

'file << i << endl;'Rob's rule:当你的意思是''\ n''时,千万不要说'endl'。见http://stackoverflow.com/questions/5492380/what-is-the-c-iostream-endl-fiasco/5492605#5492605 –

回答

2

你,你正在使用不会进入while循环:

while(!(randomLine > min) && !(randomLine < max)) 

,同时立即评估为假。你应该使用:

while(randomLine < min || randomLine > max) 

此外,为什么你所有的变量有不同的类型?这可能会导致意想不到的错误。你应该改变他们有相同的类型。

1

randomLine被初始化为0,并且仍然有值一旦到达时间,因此循环体永远不会执行。

相关问题