这是我的示例代码:
char a;
char str [20];
unsigned char b[8] ;
unsigned char c[8];
int argsread;
int i;
init_8051();
while(1)
{
printf("\n enter a 64 bit operation \n");
argsread = scanf("%s", str);
sscanf(str, "0x%x%c0x%x", b, &a, c);
printf("\n %d arguments read \n",argsread);
for(i=0;i<8;i++)
{
printf("\n %#x %c %#x\n",b[i],a,c[i]);
}
}
}
这里的问题是,当我在终端中输入以下输入时: 0x1234567890abcdef+0x1234567890abcdef
这会导致错误,其中 char 数组的输出完全错误,并且大多数数字都被追踪到 a 中,这应该是加号,我是在做一些根本错误的事情吗?
更新: 我将代码更改为以下内容:
while(1)
{
printf("\n enter a 64 bit operation \n");
argsread = scanf("%s", str);
sscanf(str, "0x%s%c0x%s", b, &a, c);
printf("\n %d arguments read \n",argsread);
printf("\n %s \n",b);
}
我将 str 的大小增加到 30,问题是程序的输出是:
1 arguments read
abcdef+0xabcdef
所以b的值不仅仅是abcdef而是整个字符串!!
更新2: 发现这段代码运行完美,但我想使用 scanf 而不是 cin 这是代码
:`#include <iostream>
using namespace std;
int main()
{
float a, b, result;
char oper, clear;
cout << "Please enter an equation: i.e 5+5 " << endl;
for (;;) {
cin >> a;
cin >> oper;
cin >> b;
if (oper == '+')
result = a + b;
else if (oper == '-')
result = a - b;
else if (oper == '*')
result = a * b;
else if (oper == '/')
result = a / b;
cout << "= " << result << endl << endl;
cin.clear();
cin.ignore();
}
} `
最佳答案
如果代码以 fgets()
开头,用户输入和错误处理会更容易。
然后使用sscanf()
、strtol()
等进行解析。
printf("\n enter a 64 bit operation \n");
char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) Handle_IOErrororEOF();
char a;
char b[17]; // use right size arrays
char c[17];
// use width of 16 and %[]
if (sscanf(buf, " 0x%16[0-9abcdef] %c 0x%16[0-9abcdef]", b, &a, c) != 3) {
Handle_Bad_Input();
}
OTOH,只需使用允许十六进制输入 "%x"
或 "%i"
unsigned long long b,c;
if (sscanf(buf, "%lli %c%lli", &b, &a, &c) != 3) {
Handle_Bad_Input();
}
<小时/>
为什么char str [20]; scanf("%s", str);
有问题:
"%s"
做了 3 件事:
1) 扫描但不保存所有前面的(0 个或更多)空白 (' '
、'\t'
、'\n '
等)。
2) 扫描并保存所有非空白。
3)最后到达一个空白。它会停止扫描并将该空白放回 stdin
中。
"%s"
说明符缺少宽度,如 "%19s"
,因此很容易溢出 str
sscanf(str, "0x%s%c0x%s", b, &a, c);
也有麻烦。
输入的第一个数字末尾和 '+'
之间没有空格,因此 "%s"
继续扫描。代码不检查 sscanf()
的返回值,然后使用 a
、b
、c
。因此,a
、b
、c
可能无法正确扫描或初始化 - 导致潜在的未定义行为。
关于c - 将字符串扫描为十六进制字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27566148/