#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char* str = malloc(10);
strcpy(str, "good");
printf("%s", str);
free(str);
return 0;
}
1), fgetc() / getc() / getchar() 全部返回一个整型值。
2), gets() 函数的使用。
不要轻易使用这个函数!不能通过它安全地保存字符串中大量的字符。如果使用它来读取大量的字符。内存会被破坏。
3), getchar() 实例
#include <iostream>
using namespace std;
int main() {
int k;
while((k = getchar()) != '\n') {
cout << "K : " << k << endl;
}
return 0;
}
a 1 t#&K : 97
K : 32
K : 49
K : 9
K : 116
K : 35
K : 38
#include <iostream>
using namespace std;
int main() {
int k;
while((k = getchar()) != EOF) {
cout << "K : " << k << endl;
}
return 0;
}
a#$ ^ io
K : 97
K : 35
K : 36
K : 32
K : 94
K : 9
K : 105
K : 111
K : 10
q
K : 113
K : 10
本文介绍了C语言中几种常见的字符串处理方法,包括使用malloc分配内存并复制字符串、使用fgetc/getc/getchar读取字符及注意事项。同时提醒开发者避免使用不安全的gets函数来防止内存破坏。

被折叠的 条评论
为什么被折叠?



