[英]Parsing a C string and storing parts of the string in variables
这篇文章可能被标记为重复,但我确实在网上搜索了这个特定案例,但我找不到任何类似的例子。 以下是我的代码的简化版本。
我将以下数据行存储在名为test.txt
的文本文件中:
12345|This is a sentence|More words here
24792|This is another sentence|More words here again
test.txt
文件中的文本将始终遵循<int>|<string>|<string>
的格式
我现在想存储由分隔符|
分隔的每个部分在一个变量中。
以下是我的尝试:
uint32_t num;
char* str1, str2;
// the data variable is a char pointer to a single line retrieved from test.txt
sscanf(data, "%d|%s|%s", &num, str1, str2);
上面的代码将检索num
的正确值,但会将第二节中的第一个单词插入str1
,将变量str2
保留为 null。 据我了解,之所以如此,是因为sscanf()
function 在遇到空格时会停止。
是否有将每个部分存储到变量中的有效方法?
如您所述, %s
使用空格作为分隔符。 使用|
作为分隔符,使用%[^|]
。 这匹配任何不包括|
的字符序列 .
而且由于num
是无符号的,你应该使用%u
,而不是%d
。
sscanf(data, "%u|%[^|]|%[^|]", &num, str1, str2);
不要忘记为str1
和str2
分配memory指向; scanf()
不会自动执行此操作。
您的变量声明也是错误的。 它需要是:
char *str1, *str2;
您的声明相当于:
char *str1;
char str2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.