2009-10-21 46 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作品的价值,因为那些在内存中的字符串是空终止的。