我不知道如何解决这个问题。它是关于从文件中逐行读取字符串,然后将每一行放入一个新的更大的字符数组中。这里的问题是后面的字符数组 (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/