我的目标是编写一个可以读取文本文件的C ++程序:
将使用命令“./a.out< textfile”
读取文本文件我到目前为止尝试的是让程序一次用“cin>> current”检查每个字符。我有一个循环。如果当前点击一个标点符号,它应该将linecount增加1.它也应该是读取字母字符,但我不知道如何计算它们。
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cctype>
using namespace std;
int main()
{
int letters; //Total number of letters per sentence
int digits; //Total number of digits
int sentencecount; //Number of sentences
float averageletters; //Average number of letters per sentence
int linecount ; //Count of lines
char current; //Current character
cin >> current;
digits = 0;
letters = 0;
while (cin)
{
if (current == '.' == '!' == '?')
linecount++;
//calcuate averages and other sentence data
//reset sentence data
if (isalpha(current))//repeat for digits
letters++;
cout << "line #" << letters << endl;
cin >> current;
}
return 0;
}
答案 0 :(得分:3)
if (current == '.' == '!' == '?')
上面的一行不符合你的想法。假设current
是感叹号。然后评估为:
if (false == '!' == '?') // The character is NOT a '.'
然后:
if (false == '?') // '!''s value is > 0, so the condition checks if true == false
最后:
if (false) // For the same reasons as above
要修复您的情况,请使用:
if (current == '.' || current == '!' || current == '?')
这使用布尔OR运算符来检查语句中的任何条件是否为真,在这种情况下进入if语句。您还可以在条件中添加括号以提高可读性。
答案 1 :(得分:0)
if(current =='。'=='!'=='?')
可能不会以他们想要的方式评估。您可能想要了解c ++运算符优先级。
你可以试试 -
if((current =='。')||(current =='!')||(current =='?'))