簡體   English   中英

字符數組不符合新大小

[英]Character array doesnt conform to new size

我不知道如何解決這個問題。 它是關於從文件中逐行讀取字符串,然后將每一行放入一個更大的新字符數組中。 這里的問題是,后一個字符數組(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 )。

我認為strlen(newStr)返回直到第一個\\ 0的字符數。 因此,您只獲得第一行,直到第一個\\ 0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM