为什么这个循环不中断
Why does this for loop not break
我正在学习使用此资源C++http://www.learncpp.com/cpp-tutorial/58-break-and-continue/
我希望这个程序在输入命中空格后结束并打印空格类型的数量。相反,您可以根据需要输入任意数量的空格。当您按回车键时,如果空格数超过 5,程序将打印 1、2、3、4 或 5。
#include "stdafx.h"
#include <iostream>
int main()
{
//count how many spaces the user has entered
int nSpaceCount = 0;
// loop 5 times
for (int nCount=0; nCount <5; nCount++)
{
char chChar = getchar(); // read a char from user
// exit loop is user hits enter
if (chChar == 'n')
break;
// increment count if user entered a space
if (chChar == ' ')
nSpaceCount++;
}
std::cout << "You typed " << nSpaceCount << " spaces" << std::endl;
std::cin.clear();
std::cin.ignore(255, '/n');
std::cin.get();
return 0;
}
控制台输入是行缓冲的。在给出 Enter 之前,库不会向程序返回任何输入。如果您确实需要逐个字符输入,您可能会找到绕过此操作的操作系统调用,但如果这样做,您将跳过有用的操作,例如退格处理。
你为什么有?
// loop 80 times
for (int nCount=0; nCount <5; nCount++)
{
}
如果您只循环 5 次,则不能添加超过 5 个空格是有意义的。也许你的意思是
// loop 80 times
for (int nCount=0; nCount <80; nCount++)
{
}
或者干脆
while(true)
{
}
std::cin.clear();
std::cin.ignore(255, '/n');
std::cin.get();
这三行将不允许您退出代码,直到 cin 停止忽略输入。你把"/n"颠倒过来,应该是""。
我为你写的:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int intSpaceCounter = 0;
string strLine;
getline(cin,strLine);
for (int i = 0; i <= strLine.length(); ++i)
{
if (strLine[i] == ' ')
{
++intSpaceCounter;
}
}
cout << "You typed " << intSpaceCounter << " spaces.";
return 0;
}
相关文章:
- 我的代码运行良好,但在游戏循环中中断
- 使用 UDP 中断 while()-循环
- 如何使用中断停止循环?
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 使用 shared_ptr 在中断时结束多线程循环
- 为什么我的 while 循环对于特定输入中断,而对于其他输入工作正常?
- 为什么循环没有中断,并且 if 条件没有按预期工作?
- C 从另一个函数中断循环
- 使用 while(1) 但在 C++ 中无法中断循环
- 输入特定数字时中断循环
- 干净编码:如何从循环中的函数调用内部中断循环
- nullptr 不会在以零结尾的字符串上中断循环
- 使用 std::weak_ptr 和别名构造函数中断循环引用:声音或有问题
- 用功能中断循环
- g++优化中断循环
- 无法使用 cin.get 来检测周期来中断循环
- 返回内部循环以C++中断循环
- OpenMP 不支持中断循环
- while语句中断循环
- 如何在Linux应用程序上使用C++中的终端输入中断循环/进程