c++ - 使用do-while循环计算字符串中的字符、单词和行| C++
问题描述
我正在尝试将一个while
对字符串中的字符、单词和行进行计数的循环转换为一个do-while
循环。
这是我的while
循环:
#include <stdio.h>
#include <string>
#include <typeinfo>
using namespace std;
int main()
{
int c;
int characters = 0;
int words = 1;
int newlines = 0;
printf("Input a string. Press enter, then ctrl+Z, then enter once more to end string.\n");
while ((c = getchar()) != EOF)
{
if (c >= 'a' && c <= 'z' || c>= 'A' && c<= 'Z')
characters++;
else if (c == ' ')
words++;
else if (c == '\n')
newlines++;
}
printf("The number of characters is %d\n", characters);
printf("The number of words is %d\n", words);
printf("The number of newlines is %d\n", newlines);
return 0;
}
我已经尝试了几个小时使用do-while
循环重复上述过程,但无济于事。
这是我到目前为止所拥有的:
#include <stdio.h>
#include <string>
#include <typeinfo>
using namespace std;
int main()
{
int c;
int characters = 0;
int words = 0;
int newlines = 0;
printf("Input a string. Press enter, then ctrl+Z, then enter once more to end string.\n");
do
{
c = getchar();
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
characters++;
else if (c == ' ')
words++;
else if (c == '\n')
newlines++;
} while (c = getchar() != EOF);
printf("The number of characters is %d\n", characters);
printf("The number of words is %d\n", words);
printf("The number of newlines is %d\n", newlines);
return 0;
}
解决方案
张贴循环有两个主要问题do
。while
第一个是您正在读取两个字符,但在循环的每次迭代中只处理字符。
第二个是它while (c = getchar() != EOF)
没有做你希望它会做的事情。由于运算符优先级,这相当于
while (c = (getchar() != EOF))
.
do
{
c = getchar(); // OK the first time, not after that.
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
characters++;
else if (c == ' ')
words++;
else if (c == '\n')
newlines++;
} while (c = getchar() != EOF); // This is bad.
即使您通过使用解决第二个问题
while ((c = getchar()) != EOF);
它仍然不好,因为该行有利于检测 EOF,但字符被忽略以进行进一步处理。
您必须将do
-while
循环更改为:
do
{
c = getchar();
if ( c == EOF )
{
break;
}
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
characters++;
else if (c == ' ')
words++;
else if (c == '\n')
newlines++;
} while (true);
如您所见,这并不是对while
循环的改进。while
从清洁度的角度来看,它比循环更糟糕。
推荐阅读
- scikit-learn - sklearn LabelEncoder inverse_transform TypeError:只能将整数标量数组转换为标量索引
- python-3.6 - 使用带有 Visual Studio 代码错误的 python 3.6 在生产 azure function 2.0 中部署
- r - 如何检查时间组是否在R中是顺序的
- c# - 通过 CloudTable.CreateQuery 创建的查询可能无法调用流利的方法
() - php - 如何防止在 PHP 中下载 MP3 文件?
- angular - 传递模块导入语句
- r - 带有 R 中日期的 if 语句 - 每年概括
- java - 实现方法 org.postgresql.jdbc4.Jdbc4Connection.getSchema()
- objective-c - Objective-C 和 Swift 用户想要的功能之间的区别?
- spring-boot - spring data arangodb - 没有可用的 MappingContext,创建名称为“resourceMappings”的 bean 时出错