<代码>strcat将其论点视为一种绝缘体。 将“条码”改为“条码”(<>条码/代码>)同样危险,我无法想象任何理由会有所助益(不意味着你重新站出来审判——每个人都在学习时犯了sil错。 因此,我们在此重申。
The reason is that it would interpret the single byte char
, plus the extra sizeof(char*) - sizeof(char)
(usually 3) bytes surrounding that char
, as a pointer, which would point to... anywhere. You have no way of knowing where it points, since 3 of those bytes are beyond your control, and thus no way of knowing whether it points to valid data.
您可以采取第二种做法:
strcat(inp, &c);
This time, you d be doing better, since &c
is an expression of type char *
and no casts are required. But again, strcat
assumes it s argument is a nul-terminated string, and since you have no way of guaranteeing a nul byte after your char
data, this won t do.
最好的办法是:
size_t len = strlen(inp); // this may already be calculated somewhere else
...
inp[len++] = c; // add c as the last character, and adjust our len
inp[len] = ; // add a new nul terminator to our string
最新资料:
实际上,我 lie。 rel=“nofollow”>fgets
,似乎正在做更多或更少的工作。 我原谅这一点,但如果这是家务劳动,教授可能不想使用<条码>fgets。 以便你能够了解如何人工操作。 然而,如果这种单质的家务劳动,fgets
确实是你重新寻找的东西。 (实际上,第三种办法正好在改写如下:<条码>fgets或<条码>fgets 类似功能。)
I would also add some other commentary on your input
function:
char* inp = "";
will point to read-only data. A flaw in the C standard (for backwards compatability) allows string literals to be assigned to char*
types instead of const char *
types as it (IMHO) should be.
There are several ways to approach this, but the best is dynamic allocation. Use the malloc
function to reserve some data, keep track of how much you ve used in your function, and use the realloc
function if you end up needing more room to store it. If you need help with that, I m sure you ll be back here (hopefully not too soon) with another question. :)
getchar()
returns an int
, because EOF
is defined to be outside the normal range of a char
. In order to distinguish between any char
and EOF
, it s best to make c
an int
. Otherwise a perfectly valid character may signal EOF
. Be sure to cast c
down to a char
when you add it to the string, though.