how to read a string from a \n delimited file

匆匆过客 提交于 2019-12-30 18:39:13

问题


I'm trying to read a return delimited file. full of phrases.

I'm trying to put each phrase into a string.

The problem is that when I try to read the file with

fscanf(file,"%50s\n",string);

the string only contains one word. when it bumps with a space it stops reading the string


回答1:


fscanf can be modified to read past spaces. The details are a bit complicated. Here is what the man page says about %[...]

Matches a nonempty sequence of characters from the specified set of accepted characters; the next pointer must be a pointer to char, and there must be enough room for all the characters in the string, plus a terminating NUL character. The usual skip of leading white space is suppressed. The string is to be made up of char-acters in (or not in) a particular set; the set is defined by the characters between the open bracket [ character and a close bracket ] character. The set excludes those characters if the first character after the open bracket is a circumflex ^. To include a close bracket in the set, make it the first character after the open bracket or the circumflex; any other position will end the set. The hyphen character - is also special; when placed between two other characters, it adds all intervening characters to the set. To include a hyphen, make it the last character before the final close bracket. For instance, `[^]0-9-]' means the set ``everything except close bracket, zero through nine, and hyphen''. The string ends with the appearance of a character not in the (or, with a circumflex, in) set or when the field width runs out.

So, %[^\n] should read everything up to the carriage return.




回答2:


fscanf(file,"%50[^\n]\n",string);
  1. Every character except \n will be consumed by [^\n]

  2. Maximum 0f 50 chars will be consumed (make sure string has space for 51 atleast)

  3. ..\n",string this makes sure that \n is also consumed so that the next call does not just return a null string.




回答3:


fscanf with %s stops reading when it finds whitespace.

Since you are reading unformatted text, you can simply use fgets, which reads until it fills the buffer you give it, it finds a newline (\n), or it reaches the end-of-file, whichever comes first.




回答4:


Avoid using scanf. As already mentioned, you should use fgets instead.

If you don't want to use a fixed-size buffer and to allow lines of arbitrary length, you can try using Chuck Falconer's public domain ggets function. (That link seems to be down right now, but archive.org has a copy.)




回答5:


intially send data using Payload_ID 00 01 02 03 ....10

use

char *pChar="" ; //for string capturing.

fprintf(fp1, "%s", strtok(pChar,"Payload_ID"));



来源:https://stackoverflow.com/questions/2718595/how-to-read-a-string-from-a-n-delimited-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!