C++——常见错误总结1.4
switch错误
以下错误,在vs/vc中有提示,但是仍可以通过编译。
在gcc编译器中,不能通过编译。
#include <stdio.h> int main(void) { int c; scanf("%d", &c);
switch(c) { case 1: int x = 0; //错误! printf("c=1"); break; case 2: printf("c=2"); break; default: printf("other"); break; }
return 0; } |
应该修改为:
#include <stdio.h> int main(void) { int c; scanf("%d", &c);
switch(c) { case 1: { int x = 0; //错误! printf("c=1"); } break; case 2: printf("c=2"); break; default: printf("other"); break; }
return 0; } |
不安全函数(scanf等)
#include <iostream> #include <string> #include <stdio.h> using namespace std; int main(void) { int num; scanf("%d", &num); system("pause"); return 0; } |
vs中不能直接使用scanf等C标准库函数
因为vs使用更安全的c11标准, 认为这类函数不安全。
这类函数正常使用时,是没有任何问题的
但是,部分黑客可能会利用其中的缺陷,开发恶意软件,对系统造成影响
解决方案:
1.方法1:使用修改项目的属性,直接使用这些“不安全”的函数。
添加: /D _CRT_SECURE_NO_WARNINGS
2.方法2:使用c11标准中的“更安全”的函数
scanf_s
gets不能使用
使用gets_s
gets是老标准C语言函数,vs使用更安全的c11标准, 使用对应的gets_s
char line[32]; gets_s(line, sizeof(line)); |
scanf不能使用
原因同上,改用scanf_s
int x; scanf_s("%d", &x); //不需要使用第3个参数,用法和scanf相同 float f; scanf_s("%f", &f); //不需要使用第3个参数, 用法和scanf相同 char c; scanf_s("%c", &c, sizeof(c)); //需要使用第3个参数, 否则有告警 char name[16]; scanf_s("%s", name, sizeof(name)); //需要使用第3个参数 int age; char name[16]; scanf_s("%d%s", &age, name, sizeof(name)); |
cin >> 的返回值
#include <iostream> #include <string> #include <Windows.h> using namespace std; int main(void) { string word; int count = 0; int length = 0; cout << "请输入任意多个单词:"; while (1) { if ((cin >> word) == 0) { //在 vs中不能通过编译 break; } count++; length += word.length(); } cout << "一共有" << count << "单词" << endl; cout << "总长度:" << length << endl; system("pause"); return 0; } |
把 if ((cin >> word) == 0) 修改为:
if ((bool)(std::cin >> word) == 0) {
或者修改为:
if (!(cin >> word)) {
getline的返回值
#include <iostream> #include <string> #include <Windows.h> using namespace std; int main(void) { string line; int lineCount = 0; int length = 0; cout << "请输入任意多行:"; while (1) { // 遇到文件结束符时, 返回NULL(0) if (getline(cin, line) == 0) { break; } lineCount++; length += line.length(); } cout << "一共有" << lineCount << "行" << endl; cout << "总长度: " << length << endl; system("pause"); return 0; } |
测试代码:
string line; int length = 0; getline(cin, line) >> length; cout << "line=" << line << endl; cout << "length=" << length << endl; |
修改:
if (getline(cin, line) == 0) {
修改为:
if ((bool)getline(cin, line) == 0) {
或者修改为:
if (!getline(cin, line)) {
if语句后面误加分号
int age; cout << "请输入年龄: "; cin >> age; if (age > 40); { cout << "大叔" << endl; } |
严格遵循代码规范,做到零警告。
以上代码在VS中编译时,会有警告warning
posted on 2022-10-16 10:57 会飞的鱼-blog 阅读(24) 评论(0) 编辑 收藏 举报 来源
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现