所以,我的问题很简单,我想创建一个函数来分离文件中的单词并解析这些单词并为这些单词创建一个特殊的想法,但是,当我尝试分离时,strcat 出现错误代币:
看代码:
#include <stdio.h>
#include <string>
#include <Windows.h>
using namespace std;
bool compile(FILE *fp)
{
char c;
char token[256];
bool _return = false;
while ((c = getc(fp)) != EOF)
{
if(isalpha(c))
{
// The error is here
strcat(token, (char*)c);
printf("%c\n", c);
}
else
{
printf("----> %c\n", c);
}
}
printf("%s\n", token);
return _return;
}
int main()
{
char *filename = "test.in";
FILE *fp = fopen(filename, "rb");
if(!fp)
{
return 1;
}
if(!compile(fp))
{
printf("ERROR...\n");
}
fclose(fp);
}
代码构建正常,但是,当我调试时,调试器转到 strcat.asm 文件:( 那么,我的错误在哪里,感谢您的帮助。 (:
-0-0-0-0-0-0-0-0-0-> 编辑 而且,当我将 strcat 更改为:
strcat(token, &c)
我从调试器收到这个错误:
Unhandled exception at 0x20E801F2 in APP.exe: 0xC0000005: Access violation (parameters: 0x00000008).
最佳答案
这是错误的:
strcat(token, (char *) c);
变量 c
不是字符串,它只是一个字符。转换为 (char *)
只是掩盖编译器错误。
如果要一次一个地向字符串中添加字符,
std::size_t pos = 0;
char buf[256];
// ...
if (isalpha(c)) {
assert(pos < sizeof(buf));
buf[pos++] = c;
}
// ...
assert(pos < sizeof(buf));
buf[pos] = '\0';
printf("buf = %s\n", buf);
或者,您知道,用简单的方法来做:
#include <string>
std::string s;
// ...
if (isalpha(c)) {
s += c;
}
// ...
printf("buf = %s\n", s.c_str());
不要费心调试 strcat()
的内部。如果您的程序在 strcat()
中崩溃,那是调用函数出错。 (即使调用 strcat()
通常也是一个错误。)
关于c++ - 带有 char 指针的 strcat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13465390/