c++ 常见问题

用vs版本时候会有很多错误
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
在vs当中应该用scanf_s
gets也是一样 应该用get_s
cin>>的返回值
#include
#include
#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的返回值 也是一样的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值