简体   繁体   English

字符数组不符合新大小

[英]Character array doesnt conform to new size

I cannot figure out how to solve this problem. 我不知道如何解决这个问题。 Its about reading a string from a file - row by row - then put every row in a new bigger characterarray. 它是关于从文件中逐行读取字符串,然后将每一行放入一个更大的新字符数组中。 The problem here is that the latter characterarray (newStr) only takes the first row from the textfile - IF one looks att the stringlenght of the new file. 这里的问题是,后一个字符数组(newStr)仅从文本文件中获取第一行-如果一个人看着新文件的字符串长度。 But i Tried to loop beyond the arrays lenght and guess what? 但是我试图循环超出数组长度,你猜怎么着? - Yes - here I found the chars from the second row. -是的-在这里,我找到了第二行的字符。

So - what did I do wrong or miss? 所以-我做错了什么或错过了什么? Why is the strlen(newStr) not conforming to the new bigger string? 为什么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;
}

this is the contents of the textfile 这是文本文件的内容

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

Here is whats printed from the consolewindow 这是从控制台窗口打印的内容

1. if looping within the bounds 1.如果在范围内循环

  I am a row in notepad

2. If looping beyond the bounds 2.如果循环越界

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

Instead of this: 代替这个:

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

write this: 写这个:

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

With <= it also copies the \\0 , which makes strlen(newStr) return only the length of the first line (because there is \\0 after the first line). 使用<=还会复制\\0 ,这使strlen(newStr)仅返回第一行的长度(因为第一行之后有\\0 )。

I think that strlen(newStr) return the number of characters till the first \\0. 我认为strlen(newStr)返回直到第一个\\ 0的字符数。 So you get only the first line till the first \\0. 因此,您只获得第一行,直到第一个\\ 0。

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

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