2012-02-16 82 views
1

我想讀取一個.txt文件,在我的文本文件中有數字但也是路徑文件夾(例如:「C:\ Documents and Settings ......」 )用空格讀取txt(C++)

我能夠在沒有任何問題的情況下讀取數字,但是當我嘗試讀取路徑時,我只是閱讀到第一個「空格」,這意味着,我只是在兩種情況下閱讀「C:\ Documents」 。我能做什麼?

//READING PARAMETERS FROM A .TXT FILE 
//double sigma; double alpha; double tau; 
//double miniter; double maxiter; double q; double m; 
//‘R’ image folder ; ‘T’ image folder; 

// input-file-stream 
// - in = (input) open the file for reading 
ifstream f ("parametros.txt", ifstream::in) ; 

// Error if it is not open properly 
if (!f){ 
    cout<<"ERROR OPENING THE FILE .TXT"<<endl; 
    exit(EXIT_FAILURE); 
} 


char *cadena = new char [100]; 
stringstream folder_T; 
stringstream folder_R; 
int iter = 1; 
while (!f.eof()){ 
    // reading the next line 
    f >> cadena ; 
    if (iter == 1){ 
     sigma = atof(cadena); 
    } 
    else if (iter == 2){ 
     alpha = atof(cadena); 
    } 
    else if (iter == 3){ 
     tau = atof(cadena); 
    } 
    else if (iter == 4){ 
     miniter = atof(cadena); 
    } 
    else if (iter == 5){ 
     maxiter = atof(cadena); 
    } 
    else if (iter == 6){ 
     q = atof(cadena); 
    } 
    else if (iter == 7){ 
     m = atof(cadena); 
    }  
    else if (iter == 8){ 
     folder_T<<gets(cadena);  // Only 「C:/Documents」 is returned 
    } 
    else if (iter == 9){ 
     folder_R<<gets(cadena);  // Only 「C:/Documents」 is returned 
    } 

    iter = iter + 1; 

}// fin while 
f.close(); 
+1

你聽說過switch語句嗎?閱讀http://msdn.microsoft.com/en-us/library/k0t5wee3(v=vs.80).aspx – shift66 2012-02-16 09:03:15

+1

['while(!f.eof())'幾乎總是錯]](http:/ /www.parashift.com/c++-faq-lite/input-output.html#faq-15.5)。你從哪裏學到的? – 2012-02-16 09:55:33

+0

While-if pattern,我可以請你考慮一下爲什麼。 – 2012-02-16 14:16:24

回答

3

您沒有閱讀完整行cadena。這樣做

getline(f, cadena); 

此外,你不應該使用gets()。您將在cadena中擁有完整的產品線。

+0

擴大一點點:while(f.getline(cadena,sizeof(cadena)){...} – stefaanv 2012-02-16 09:13:34