我正在尝试计算文件中特定字符的数量。我遇到的问题是输出是一个巨大的数字,与文件中每个字母的数量不匹配。
RainOrShine.txt
RRCSSSCSCRRRCSSSCSSRSCCRCRRCSS
SSSCCSSSCCSSSCCSSSCRCRCCSSSSSS
SSSSCSSSCSSSCRRCCCSSSSSCSSSSCS
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
string filelocation = "C:/Users/erizj/OneDrive/Documents/RainOrShine.txt";
ifstream textfile;
textfile.open(filelocation.c_str());
char weather[3][30];
int countR,countC,countS = 0;
if (!textfile)
{
cout << "Error opening the file.";
return 0;
}
else
{ // Read weather data in from file
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 30; col++)
{
textfile >> weather[row][col];
if(weather[row][col]=='R'){
countR++;
}
if(weather[row][col]=='C'){
countC++;
}
if(weather[row][col]=='S'){
countS++;
}
}
}
}
cout<<"Rainy Days during 3-Month Period: "<<countR<<endl;
cout<<"Cloudy Days during 3-Month Period: "<<countC<<endl;
cout<<"Sunny Days during 3-Month Period: "<<countS<<endl;
//cout<<"Rainy Days in June: "<<
textfile.close();
return 0;
}
输出:
3个月期间的雨天:4201688
3个月期间的阴天:6356911
3个月期间的晴天:50
它与我设置的计数器有关吗?提前谢谢。
答案 0 :(得分:2)
int countR,countC,countS = 0;
初始化countS
,但countR
和countC
未初始化。
答案 1 :(得分:0)
您的程序假设数据中有固定数量的行和列。这可能是个问题。
我建议采用更灵活的方法,不要假设数据的组织方式或数据量。
让我们为我们的数据库定义一个结构。数据可以按顺序存储,但我们需要数据结构是动态的:std::vector
。
现在在进行任何分析之前读入数据:
std::vector<char> database;
std::string text_line; // Easier to read in a lot of data
while (getline(data_file, text_line))
{
std::string::size_type index;
const std::string::size_type length = text_line.length();
for (index = 0; index < length; ++index)
{
const char c = text_line[index];
if ((c == 'R') || (c == 'S') || (c == 'C'))
{
database.push_back(c);
}
}
}
由于数据被读入数据库,您可以对其进行分析:
unsigned int duration = 0;
unsigned int rain_quantity = 0;
unsigned int sunny_quantity = 0;
unsigned int cloudy_quantity = 0;
// Set up the duration for the first 30 days
duration = 30;
if (database.size() < 30)
{
duration = database.size();
}
for (unsigned int index = 0; index < duration; ++index)
{
const char c = database[index];
if (c == 'C')
{
++cloudy_quantity;
}
else
{
if (c == 'R')
{
++rain_quantity;
}
else
{
++sunny_quantity;
}
}
}
您无需从文件中读取数据即可执行其他分析。
答案 2 :(得分:0)
您需要分别初始化所有整数变量
int countR = 0, countS = 0, countT = 0;