简体   繁体   English

C ++将文本从文件放置到char

[英]C++ putting text from a file to a char

So I have multiple words in a text file and I want to put all of them in a char. 所以我在文本文件中有多个单词,我想将所有单词都放在一个字符中。 The problem is that it doesn't keep the space between the words too. 问题在于,单词之间也没有保持空格。 My code: 我的代码:

ifstream f("file.txt");
char a[100];
int i=0;
while(f){
f>>a[i];
i++;
}

'>>' stream operator do not detect space in file. “ >>”流运算符不检测文件中的空间。 you we have cin.get(charVariable); 您有cin.get(charVariable); function for it. 功能。 in your case it will be f.in(a[i]); 在你的情况下它将是f.in(a[i]);

This will solve your problem; 这将解决您的问题;

ifstream f("File.txt");
    char a[100];
    int i = 0;
    while (f){
        f.get(a[i]); //use it instead of f>>a[i];
        i++;
    }

This happens because your'e reading the file word by word. 发生这种情况是因为您正在逐字读取文件。 You should use the std::string contents function to read the whole text char by char (space char included). 您应该使用std :: string内容函数按char(包括空格char)读取整个文本char。

Please read Nemanja Boric answer at This Page 请在此页阅读Nemanja Boric的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM