c++ - 如何让循环重复输入的行数?

标签 c++ for-loop

下面的程序将重复宽度,但我也想重复高度输入。

 int main () 
 {

 int height;
 int width;
 int count;
 int hcount;
 string character;

 cout << "input width" << endl;
 cin >> width;
 cout << "input height" << endl;
 cin >> height;
 cout << "input character" << endl;
 cin >> character;

      for (hcount = 0; hcount < height; hcount++);
     {
     for (count = 0 ; count < width; count++) 
     cout << character;
     cout << endl;
     }

我需要添加另一个 for 循环吗?我不知道如何让它重复。我尝试添加另一个 for 循环但更改了高度和宽度的顺序:

          for (count = count < width; count++)
              { (count = count < height; hcount++)
                cout < character;
                cout << endl;

但没有运气。

最佳答案

for 循环在它后面的单个语句上运行 so

for (hcount = 0; hcount < height; hcount++);

相当于

for (hcount = 0; hcount < height; hcount++)
    ;

所以你的第一个循环什么都不做。如果您删除结尾的分号

for (hcount = 0; hcount < height; hcount++)

您将获得所需的嵌套循环。

还要注意

for (count = 0 ; count < width; count++) 
    cout << character;
    cout << endl;

实际上是

for (count = 0 ; count < width; count++) 
    cout << character;
cout << endl;

如果您希望这两行都在内部循环中执行,您需要将它们放在大括号内 {}

for (hcount = 0; hcount < height; hcount++) {
    for (count = 0 ; count < width; count++) {
        cout << character;
        cout << endl;
    }
}

关于c++ - 如何让循环重复输入的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19743042/

相关文章:

c++ - 使用 CMake 创建库、安装它并链接到另一个项目的正确方法

for循环中特定元素的Javascript数组组

java - 从循环中将 null 放入数组

javascript - 我可以使用串联的 var+array_value 作为 jquery 中的选择器,即 $ ("#var+array_value")

c++ - Qt 5.0方法原生事件语法需要解释

c++ - 微过滤器:通过通知阻止应用程序

python - 使用 C++,如何在 Qt Designer 中运行 python 文件?

matlab - 在matlab中检查没有for循环的数组中的成员资格

javascript - For 循环出现不足

c++ - 如何将timestamp_t转换为实际时间?