简体   繁体   中英

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. 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?

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

  I am a row in notepad

2. If looping beyond the bounds

  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).

I think that strlen(newStr) return the number of characters till the first \\0. So you get only the first line till the first \\0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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