c 编程,从文件 IO 中读取一个字符串并计算该字符串的长度
我编写了以下代码来读取文本文件的第一行并计算该字符串的大小,但是计算出的大小比我在文本文件上看到的实际尺寸大1个。例如,此字符串:SAM,我的代码计算大小4;但是,SAM的大小为3或Hello我的代码计算尺寸6,我想知道我的代码有什么问题:
FILE * inp = fopen("name.txt", "r");
char nameArr[30];
fgets(nameArr, 30, inp);
int i;
for(i = 0; nameArr[i] != '\0' && nameArr[i] != '\n'; ++i)
{
}
if(nameArr[i-1] == ' ')
--i;
printf("i is %d\n", i);
fclose(inp);
如果这里if(namearr [i-1] ==''),我认为问题是什么。
,但我无法修复
I wrote the following code to read the first line of the text file and calculate the size of that string, but the calculated size is 1 number greater than the real size that I see on the text file. For example, this string: SAM, my code calculates the size 4; however the size of SAM is 3 or for Hello my code calculates the size 6, I'm wondering what is wrong with my code:
FILE * inp = fopen("name.txt", "r");
char nameArr[30];
fgets(nameArr, 30, inp);
int i;
for(i = 0; nameArr[i] != '\0' && nameArr[i] != '\n'; ++i)
{
}
if(nameArr[i-1] == ' ')
--i;
printf("i is %d\n", i);
fclose(inp);
I think the problem if here if(nameArr[i-1] == ' ')
but I cannot fix it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我怀疑你的意思是
我也必须在某个地方声明另一个,在这种情况下,将其名称更改为其他名称
I suspect you mean
There must be another i declared somewhere too, in which case change the name of this i something else