C 仅将指针中的选定部分与另一个指针一起使用
所以基本上我想从键盘上读一段文字,我知道它的格式如下:“1 somewords”,其中somewords是一个特定的单词。问题是我不知道如何从指针访问特定的部分。 例如,如果我跑步C 仅将指针中的选定部分与另一个指针一起使用,c,pointers,C,Pointers,所以基本上我想从键盘上读一段文字,我知道它的格式如下:“1 somewords”,其中somewords是一个特定的单词。问题是我不知道如何从指针访问特定的部分。 例如,如果我跑步 `printf("%s",myPointer); 我的输出将仅为1(缺少下一部分)。 我尝试将“”后面的部分分配给另一个指针,但似乎不起作用 scanf("%s",operatie); //if , for example operatie="1 dana" if(operatie[0]=='1')
`printf("%s",myPointer);
我的输出将仅为1(缺少下一部分)。
我尝试将“”后面的部分分配给另一个指针,但似乎不起作用
scanf("%s",operatie); //if , for example operatie="1 dana"
if(operatie[0]=='1') {
char *h=(operatie+1);
printf("%s",h);
} // h will be 0.
问题在于scanf()
<代码>%s将在第一个空格处停止(在读取1
之后)。因此,输入的其余部分根本不被读取
如果你想读一行,使用<如果输入缓冲区有足够的空间,code>fgets()也将读取换行符。因此,您可能需要删除它
例如
在我看来,您的字符串在首字母1之后包含一个空字符。你能在调试器中查看if吗?或者,您可以打印转换为整数的前几个字符以查看其值吗
printf(“%d%d%d\n”),(int)运算符[0],(int)运算符[1],(int)运算符[2])
@RichardSt Cyr我收到以下输出:49 00@PetruGurita如何标记输入的结尾?@RichardSt Cyr和“enter”键盘查看@l3x的答案。从打印的第一个0可以看出,说明是正确的,建议应该可以正常工作。
scanf("%s",operatie); //if , for example operatie="1 dana"
char operatie[256];
if (fgets(operatie, sizeof operatie, stdin) == NULL) {
/* handle error */
}
/* Remove the trailing newline, if present */
char *p = strchr(operatie, '\n');
if (p) *p = 0;