添加字符串末尾为空
我有一个声明为 char Sentence[100] 的字符串; 在一个循环中,我从 txt 文件中读取不同的句子,我试图这样做:
sentence = strtok (sentencefromtxtfile," ,.-");
//seperating word by word in a loop
我可以做到。但有一个小问题。假设sentecenfromtxtfile 的长度仅为10。示例:
sentencefromtxtfile ="John" ->如果为 NULL,则为 5 个字符。但strtok函数无法注意到NULL ch。所以我的句子变量是这样的:
John ÿ( ÕŒ•vÍ>È àı~øş( j (total 100 char)
那么我该如何解决这个问题呢?我的意思是,我可以调整句子的长度吗?因为它是固定的并且 100.. 无论如何,对不起我愚蠢的英语。我希望你们明白我的意思吗?提前致谢..
I have a string declared char sentence[100];
In a loop, I read different sentences from a txt file and I'm trying to do this:
sentence = strtok (sentencefromtxtfile," ,.-");
//seperating word by word in a loop
And I can do. but there is a little problem. Lets say the lenght of sentecenfromtxtfile is just 10. Example:
sentencefromtxtfile ="John" -> with NULL, it is 5 character. But strtok function cant notice the NULL ch. so my sentence variable is being like this:
John ÿ( ÕŒ•vÍ>È àı~øş( j (total 100 char)
so how can I fix that? I mean, can I adjust the length of the sentence ? cos it is fix and 100.. Anyway, sorry for my stupid english. I hope you guys got what I mean? thanks in advance..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在填充缓冲区之前使用
\0
字符预填充缓冲区:这应该可以解决您的问题,因为
strtok()
未触及的所有字符都将是NUL
。You can prefill your buffer with
\0
characters before populating it by issuing:This should solve your problem, since all the characters
strtok()
leaves untouched will beNUL
.char[100]
是一个包含 100 个字符的数组,而不是字符串。您可以考虑使用std::string
。char[100]
is an array of 100 char's, not a string. You may consider usingstd::string
.