c++ - 字符数组不符合新的大小

标签 c++ arrays strlen

我不知道如何解决这个问题。它是关于从文件中逐行读取字符串,然后将每一行放入一个新的更大的字符数组中。这里的问题是后面的字符数组 (newStr) 只从文本文件中获取第一行——如果有人看一下新文件的字符串长度。但是我试图循环超出数组长度并猜猜是什么? - 是的 - 我在这里找到了第二行的字符。

那么 - 我做错了什么或错过了什么?为什么 strlen(newStr) 不符合新的更大的字符串?

void read3() {

   const char* FILE_NAME = "myfile2.txt";
   std::ifstream infil;
   infil.open(FILE_NAME);

   char ch[25];
   char newStr[200];

   for (int i = 0; i < 200; i++) {
       newStr[i] = 0;
   }
   for (int i = 0; i < 25; i++) {
       ch[i] = 0;
   }

   int pos = 0;
   while (infil.getline(ch, 25)) {
       unsigned int i;
       for (i = 0; i <= strlen(ch); i++) {
           newStr[pos + i] = ch[i];
       }
       pos += i;
   }

   for (unsigned int i = 0; i < strlen(newStr); i++) {
       std::cout << newStr[i];
   }
   std::cout << std::endl;

   // a second print of newStr beyond the loop to see if there are characters
   for (unsigned int i = 0; i < strlen(newStr) + 24; i++) {
       std::cout << newStr[i];
   }

   std::cout << "\nlength of newStr: " << strlen(newStr);

}

int main() {

  read3();

return 0;
}

这是文本文件的内容

 I am a row in notepad
 I am the second row :-)    

这是控制台窗口打印的内容

1。如果在边界内循环

  I am a row in notepad

2。如果循环越界

  I am a row in notepad[]I am the second row :-)     

最佳答案

取而代之的是:

for (i = 0; i <= strlen(ch); i++) {

这样写:

for (i = 0; i < strlen(ch); i++) {

<=它还复制了 \0 ,这使得 strlen(newStr)只返回第一行的长度(因为第一行后面有\0)。

关于c++ - 字符数组不符合新的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23572706/

相关文章:

C : how do I printf "the square root of 1764 is 42 and * in ascii"?

c++ - 具有混合依赖性的 Makefile 模式规则

c++ - CascadeClassifier::detectMultiScale 不适用于 C++

php - 删除 JSON 文件的 key

c - static size_t strnlen(const char *s, size_t max) -- 为什么是静态返回值?

C++11 char16_t strlen 等效函数

c++ - 有选择地禁用已检查的迭代器

c++ - 计算 vector<vector<Object>> 中重复元素的出现次数

javascript - 用数组行数据填充 div 内容,通过单击按钮选择 - 只返回最后一行

c - 从数组中获取 C 中某些值的内存地址