2017-05-05 141 views
-2

当我一次读取一个字符的文本文件,然后将该字符发送到一个字符串(这是一个字符数组)它似乎工作,输出显示正确,但然后崩溃。为什么?C++通过char将Char文件读入字符串;崩溃

第二个问题:它似乎没有为字符串(这是一个字符数组)添加空格。为什么?

#include <iostream> 
#include <fstream> 
#include <string> 
#include <iomanip> 
#include <cctype> 
using namespace std; 

int main() 
{ 
    int SIZE = 0; 

    char text; 
    string textArray; 

    fstream inFile("text.txt"); //opens text.txt 

    //checks if file was opened 
    if (!inFile) 
    { 
     cout << "Error opening the file.\n"; 
     return 0; 
    } 

    //reads each character then adds the character to the array 
    while (inFile >> text) 
    { 
     //if you coment out line 46 and 47 the program wont crash 
     textArray[SIZE] = text; //comment out // doesnt add white spaces 
     cout << textArray[SIZE]; //comment out // the output form this is the text.txt but no white spaces 
     SIZE++; 
    } 
    inFile.close(); //closes text.txt 

    cout << SIZE; //output the size of the array 

    return 0; 
} 
+0

您正在使用不存在的'[]'覆盖字符串中的字符,因为您的字符串是使用*零*长度创建的。使用'push_back()' – Galik

+0

谢谢,这是与向量?我知道矢量,但这是一个初级班,矢量不包括在内。无论如何要做到这一点没有载体? – Edix

+0

它与'std :: string'的'std :: vector'相同。你应该找到一个教程,或者更好的是还能找到一本好书,并通过它来完成。 – Galik

回答

2

When I am reading a text file one character at a time then sending that character to a string (which is an array of characters) it seems to work and the output shows correctly'ish but then it crashes. Why?

现在可以正确处理你的原因是因为运气。默认构造

string textArray; 

为空。这个实现可能会为字符输入留出一些空间,但它不必这样做。如果你想推字符到这个字符串每次从流中读取字符的结束,你可以做这样的事情:

while (inFile >> text) 
{ 
    cout << text; 
    textArray += text; 
} 

然后输出的字符串,使用尺寸:

cout << textArray.size(); 

It doesn't appear to add white spaces to the string (which is an array of characters). Why?

这是因为C++流读取文本的方式。当输入流中的字符或字符串通过

myInputStream >> myChar; 

myInputStream >> myString; 

读取它给你,你得到的字符或字符串之前可以跳过任何前导空格。这由流标志std::ios_base::skipws控制。要禁用此行为,请致电:

inFile.unsetf(std::ios_base::skipws); 
// OR 
inFile >> std::noskipws; 

要重新启用此行为,请致电:

inFile.setf(std::ios_base::skipws); 
// OR 
inFile >> std::skipws; 
1
textArray[SIZE] = text; 

它是不确定的行为写入位置SIZE当字符串的大小小于或等于SIZE。追加角色

一个正确的方法是:

textArray.push_back(text); 

你不需要SIZE可变的。字符串的大小可以从textArray.size()获得。

+1

为什么不只是'textArray + = text'? – Tas

+0

@Tas这些操作完全相同。 – cdhowie

+2

@Tas有多种方法可以为这个猫创建皮肤:'push_back','append','operator + ='和'operator +'。这真是一个品味的问题。 – InternetAussie

0

it crashes. Why?

您尝试尚未字符串的一部分访问地址:

textArray[SIZE] = text;  SIZE++; 

您可以使用std::string.push_back(char c)

It doesn't appear to add white spaces to the string (which is an array of characters). Why?

尝试:

fStreamVar >> std::noskipws; 

右后你打开文件。

+0

如果我正确解释你的输出是跳过空格。然而,事实上他们是在那里的字符串?我试图在打开文件后立即添加它,但它给了我错误:\t [错误]在';'之前声明中的qualified-id代币 – Edix

+0

我认为这并不明确,这是为实际的fstream变量。现在就试试。 –

+1

是的,我想,所以我把它放在我的while循环中,它工作。谢谢! – Edix

0

感谢所有的回信大家下面是我一直在寻找的解决方案。

while (inFile >> std::noskipws >> text) 

textArray += text; 

我现在明白为什么它是做它在做什么。非常感谢!我的问题是我刚刚完成与int的数组,并切换到字符和字符串翘曲我的大脑。

谢谢大家!