Question

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 :-)     
Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top