循环C++"Statement has no effect"警告?

C++ for loops "Statement has no effect" warning?

本文关键字:effect 警告 no has C++ Statement 循环      更新时间:2023-10-16

所以我刚开始用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(尽管您应该查找 --bb-- 之间的差异以了解该语句的实际工作原理)。 也就是说,更口语化的方式是这样的:

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 通常不是一个好主意,您可能需要用户稍后输入的值。