【问题标题】:Read File and store in a array of chars - c++读取文件并存储在字符数组中 - c++
【发布时间】:2018-11-10 18:08:32
【问题描述】:

我正在尝试打开一个文件并将其中的信息保存在一个字符数组中,但是我没有得到它。要保存在字符串中,请使用:

int main(){
string line1;
ifstream myfile;
myfile.open("example.txt");

if(!myfile){
   cout<<"Unable to open the file."<<endl;
   exit(0);
}
while(getline(myfile,line1)){
   ReadFile(myfile);
}

}

而且它有效。 当我使用一个字符数组时,我的代码是这样的:

int main(){
int size=100;
char line1[size];
ifstream myfile;
myfile.open("example.txt");

if(!myfile){
   cout<<"Unable to open the file."<<endl;
   exit(0);
}
while(myfile.peek()!EOF){
   line1[size]->ReadFile();
}

}

ReadFile 函数是这样的:

void ReadFile(ifstream &is){
   char aux[100];
   is.getline(aux,100);
}

【问题讨论】:

  • myfile.peek()!EOF 似乎不对。 line1[size]-&gt;myfile; 也很奇怪。
  • 那么不要使用字符数组 - 在这里使用字符串是正确的。此外,char line1[size]; 不是有效的 C++ 代码。
  • 我在其他程序中使用过它并且它有效。你有什么建议吗? @Quimby
  • @NeilButterworth 我需要使用 chars 来实现另一个计算文件中字符数的函数
  • 使用字符串流读取整个文件。 stackoverflow.com/questions/2602013/…

标签: c++ arrays char readfile ifstream


【解决方案1】:

要读取字符数组或文本,您可以使用std::getlinestd::string

std::string text;
std::getline(myfile, text);

处理文件中的文本行:

std::string text;
while (std::getline(myfile, text))
{
  Process_Text(text);
}

不要使用字符数组,因为它们会溢出。此外,您必须使用strcmp,而不是使用== 进行比较。始终验证您的字符数组是否由 nul 字符 '\0' 终止,否则字符串函数将超出您的数组,在找到 nul 之前不会停止。

编辑 1:空格分隔
要读取以空格分隔的文本,请使用:

std::string text;
myfile >> text;

编辑 2:计算字符串中的字符数
您可以使用另一个数组来计算字符串中的字符数。

unsigned int frequency[128] = {0}; // Let's assume ASCII, one slot for each character.
// ... read in string
const size_t length(text.length());
for (size_t index = 0; index < length; ++index)
{
  const char letter = text[index];
  ++frequency[letter];
}

【讨论】:

  • 然后我可以使用字符串文本来统计每个字符有没有文本?
  • 查看我的编辑 2
猜你喜欢
  • 2020-05-25
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多