循环C++"Statement has no effect"警告?
C++ for loops "Statement has no effect" warning?
所以我刚开始用C++学习编程,目前我正在搞砸基本的控制台程序。我想做一个小垃圾邮件程序。这是代码:
#include <iostream>
#include <string>
using namespace std;
string a;
int b;
void repetition(){
cout << "Please enter the number of time you want the text to be spammed" << endl;
cin >> b;
}
void text(){
cout << "Please enter the text you want to spam." << endl;
cin >> a;
for(;b == 0;){
cout << a << endl;
b - 1;
}
}
int main()
{
cout << "Welcome to your auto-spammer!!" << endl;
repetition();
text();
return 0;
}
我收到警告,指出"语句无效",用于第 20 行的 for 语句。我想知道为什么以及如何解决这个问题。谢谢。
for
循环在第二个语句为 true 时执行。所以除非你输入 0
,否则它永远不会执行。
该警告适用于b - 1;
。这将读取 b
的值,减去 1,并且对结果没有任何作用。你可能的意思是b = b - 1;
(也可以写成b -= 1;
或--b;
)。
我猜这是第 20 行:
b - 1;
这条线本身没有任何作用。b-1 的结果永远不会分配给任何东西。
尝试 --b
,这会将 b 递减 1 并将该操作的结果重新分配给 b。
在text()
中,b-1
确实什么都不做,你可能的意思是--b
。 第一个返回一个右值,然后丢弃该值,而第二个返回 b
1 并导致b
(尽管您应该查找 --b
和 b--
之间的差异以了解该语句的实际工作原理)。 也就是说,更口语化的方式是这样的:
for(; b > 0; --b) //Also keep in mind that the second section of a for statement
//is the continue condition, not exit
cout << a << endl;
你想打印文本N次,所以使用的正确循环是:
for (int i=0; i < b; i++)
cout<<a<<endl;
修改 b 通常不是一个好主意,您可能需要用户稍后输入的值。
相关文章:
- 警告处理为错误这里有什么问题
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- cppcheck在const std::string[]上引发警告
- GCC对可能有效的代码抛出init list生存期警告
- 如何在BST的这个简单递归实现中消除警告
- 关于std::move的使用,是否有编译警告
- g++ 在某个类成员未初始化时不发出警告
- 如何处理来自核心指南检查器的关于gsl::at的静态分析警告
- 使用typeid警告未使用的变量
- 示例C++项目编译中的警告
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 如何修复编译器警告 C6386 和 C6385?
- 返回语句后的代码,没有警告
- 获取隐式转换溢出从无符号到已签名的警告
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 在未链接的部分上生成警告
- 警告 C4552:">>":未使用表达式的结果
- 禁止显示由于常量为零而比较始终为假的警告
- 如何在过载时强制"statement has no effect"警告==
- 循环C++"Statement has no effect"警告?