C语言 strtok 不丢弃换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16677800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
strtok not discarding the newline character
提问by Nathan
so I have an input file with a bunch of names and numbers. I started using strtok to break up the string so that I can extract all the data out of each string. Everything seems to be working correctly, but for some reason it's not discarding the newline character.
所以我有一个输入文件,里面有一堆名字和数字。我开始使用 strtok 来分解字符串,以便我可以从每个字符串中提取所有数据。一切似乎都正常工作,但出于某种原因,它并没有丢弃换行符。
int procFile(PERSON **data, FILE* fpFile)
{
// Local Declaration
char temp[1000];
char proc[15];
char *entry;
char *loc;
int success = 0;
// Statement
if(fgets(temp, sizeof(temp), fpFile))
{
(*data) = aloMem(); // free
entry = temp;
loc = strtok(entry, " ()-");
strcpy(proc, loc);
loc = strtok(NULL, " ()-");
strcat(proc, loc);
loc = strtok(NULL, " ()-");
strcat(proc, loc);
sscanf(proc, "%ld", &(*data)->phone);
loc = strtok(NULL, "Brown, Joanne
1South, Frankie
1Lee, Marie
1Brown, Joanne
1Trapp, Ada Eve
1Trapp, David
1White, D. Robert
1Lee, Victoria
1Marcus, Johnathan
1Walljasper, Bryan
1Trapp, Ada Eve
1Brown, Joanne
1Andrews, Daniel
");
strcpy((*data)->name, loc);
success++;
printf("%s1", (*data)->name);
}
return success;
}// procFile
I tried printing the results to see if it's working correctly and this is my output.
我尝试打印结果以查看它是否正常工作,这是我的输出。
char *newline = strchr( temp, '\n' );
if ( newline )
*newline = 0;
It's printing the 1after each name on a newline, rather than right after the name. Can someone explain to me how I can fix the problem?
它1在换行符上打印每个名称之后,而不是在名称之后。有人可以向我解释如何解决问题吗?
回答by AlexK
Add \r \n and perhaps \t to your list of delimiters in strtok
将 \r \n 和 \t 添加到 strtok 中的分隔符列表中
回答by John Bode
Before tokenizing temp, get rid of the newline as follows:
在标记化之前temp,按如下方式去掉换行符:
strchrsearches tempfor the newline character, and returns a pointer to it (or NULL if the newline character isn't found). We then overwrite the newline with a 0 (string terminator).
strchr搜索temp换行符,并返回指向它的指针(如果找不到换行符,则返回 NULL)。然后我们用 0(字符串终止符)覆盖换行符。
回答by AlexK
According to man fgets:
根据man fgets:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.
fgets() 从流中读取至多小于 size 的字符,并将它们存储到 s 指向的缓冲区中。阅读在 EOF 或换行符后停止。如果读取换行符,则将其存储到缓冲区中。
That's where you are getting your newlines from.
那就是你从那里得到换行符的地方。

