C++ 编译错误 error: ‘cout‘ was not declared in this scope (摄氏度与华氏度的转换)

本文介绍了解决C++程序中使用cout和cin时出现的编译错误问题。通过添加命名空间std,解决了未声明的错误,并给出了正确的代码示例。

练习c++的输入输出时,编译遇到错误:

【error: 'cout' was not declared in this scope
    error: 'cin' was not declared in this scope】

原错误代码如下:

#include<stdio.h>
#include<iostream>
int main(){
    float f,c;       //为了输出带精度的小数
    cout << "转换前的华氏温度为:";
    cin>>f;
    c = 5*(f-32)/9;
    cout << "转换后的摄氏温度为:" <<c;
    return 0;

}

不能成功运行,会报上图的错。

经查找后发现是命名空间的问题,为了将c++和c区分开,规定c++的头文件都没有后缀.h,当时用iostream的时候(预定义的对象 cin 和cout是 iostream 类的一个实例),就需要用namespace std来配合,才能使用cin或cout的这种标识符。

代码加上命名空间(更改后的正确代码):

#include<stdio.h>
#include<iostream>
//下面一行为增加的命名空间
using namespace std;
int main(){
    float f,c;
    cout << "转换前的华氏温度为:";
    cin>>f;
    c = 5*(f-32)/9;
    cout << "转换后的摄氏温度为:" <<c;
    return 0;
}

编译无错误,运行截图如下:

参考文章:【https://www.runoob.com/cplusplus/cpp-basic-input-output.html

               https://blog.csdn.net/fsz520w/article/details/82561795

### `error: ‘strlen’ was not declared in this scope` 的解决方法 在C++编程中,若出现 `'strlen' was not declared in this scope` 错误,通常表示编译器无法识别 `strlen` 函数。该函数定义在 `<cstring>`(C++标准库中的对应版本)或 `<string.h>`(C语言头文件)中。在C++项目中使用时,应优先考虑使用 `<cstring>` 以确保命名空间和兼容性[^2]。 #### 正确包含头文件 确保在源代码中正确包含了 `cstring` 头文件: ```cpp #include <cstring> ``` 如果使用的是C语言环境,则应包含: ```c #include <string.h> ``` 在C++中推荐使用 `std::strlen` 或通过 `using namespace std;` 后直接调用 `strlen`。例如: ```cpp #include <iostream> #include <cstring> int main() { char str[] = "Hello World"; std::cout << "Length: " << std::strlen(str) << std::endl; return 0; } ``` #### 使用命名空间 如果在代码中使用了 `using namespace std;`,则可以直接调用 `strlen` 而不需要加 `std::` 前缀: ```cpp #include <iostream> #include <cstring> using namespace std; int main() { char str[] = "Test"; cout << "Length: " << strlen(str) << endl; return 0; } ``` 此方式适用于教学或小型项目,但在大型项目中建议使用 `std::strlen` 以避免命名冲突[^2]。 #### 替代方案:手动实现字符串长度计算 若目标平台不支持 `strlen`,可以手动实现一个简易版本的字符串长度计算函数: ```cpp size_t my_strlen(const char *str) { size_t length = 0; while (*str++) length++; return length; } ``` 该函数遍历字符数组直到遇到空字符 `\0`,并返回其长度。 ---
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wyn_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值