2009-10-21 34 views
0

將字符串寫入文件中有一點問題, 如何將字符串寫入文件並能夠將其視爲ascii文本? 因爲我能夠做到這一點,當我設置str的默認值,但不是當我輸入str數據時 謝謝。如何將字符串讀取到文件中C++

#include <iostream> 
#include <fstream> 
#include <cstring> 
using namespace std; 

int main() 
{ 
    fstream out("G://Test.txt"); 

    if(!out) { 
     cout << "Cannot open output file.\n"; 
     return 1; 
    } 
    char str[200]; 
    cout << "Enter Customers data seperate by tab\n"; 
    cin >> str; 
    cin.ignore(); 
    out.write(str, strlen(str)); 
    out.seekp(0 ,ios::end); 
    out.close(); 

    return 0; 
} 
+1

只是一個旁註。具有:char str [200];然後從輸入中讀入文本是一個壞主意。當有人輸入超過200個字符時,你的程序將表現爲未定義並可能崩潰 – Toad 2009-10-21 17:38:45

+0

'std :: string'可能設計不好,但它是你的朋友。如果'str'是一個'std :: string','cin >> str'就可以正常工作。 – 2009-10-23 19:53:16

回答

8

請使用std::string

我不知道你的情況的具體問題是,但>>只讀取到第一個分離器(這是空白); getline將讀取整個行。

+2

肯定值得注意的是,帶有字符串的<< and >>對於空白行爲有不同的表現。 +1 – 2009-10-21 18:58:09

1

請注意>>操作符會讀取1個單詞。

std::string word; 
std::cin >> word; // reads one space seporated word. 
        // Ignores any initial space. Then read 
        // into 'word' all character upto (but not including) 
        // the first space character (the space is gone. 

// Note. Space => White Space (' ', '\t', '\v' etc...) 
1

您正處於錯誤的抽象層次。另外,在關閉文件之前,不需要在文件結尾seekp

您想要讀取一個字符串並寫入一個字符串。作爲帕維爾Minaev說,這是直接通過std::stringstd::fstream支持:

#include <iostream> 
#include <fstream> 
#include <string> 

int main() 
{ 
    std::ofstream out("G:\\Test.txt"); 

    if(!out) { 
     std::cout << "Cannot open output file.\n"; 
     return 1; 
    } 

    std::cout << "Enter Customer's data seperated by tab\n"; 
    std::string buffer; 
    std::getline(std::cin, buffer); 
    out << buffer; 

    return 0; 
} 

如果你想用C寫,用C.否則,把你所使用的語言的優勢。

+0

我會使用'std :: ofstream'寫作。 – sbi 2009-10-23 09:26:09

+0

謝謝。編輯。我習慣於使用fstream。 – 2009-10-23 19:37:37

0

我不能相信沒有人發現問題。問題在於,您對未以空字符結尾的字符串使用strlenstrlen將繼續迭代,直到它找到一個零字節,並且可能返回不正確的字符串長度(或程序可能崩潰 - 這是未定義行爲,誰知道?)。

答案是零初始化您的字符串:

char str[200] = {0}; 

提供自己的字符串作爲str作品的價值,因爲那些在內存中的字符串是空終止的。

相關問題