我到处搜索,找不到解决我遇到的这个问题的方法。我在命令行上从 stdin 获取输入并使用我的程序进行一些计数。
我正在输入一个不超过 100 行且每行不超过 20 个单词的文件。因此,我有一个包含 2000 个元素的数组和一个包含一个 int 和一个包含 100 个元素的数组的结构。
我的目标是计算字数、行数和字节/字符数(已完成)。我还希望将每个单词读入一个数组,然后找出每个单词所在的行。
示例输出类似于:
a:1, 2, 4
This: 1, 2
struct: 2, 3, 4
这是我的测试文件:
This is a test file
This file contains a struct
The struct with a datatype of wordBlock that contains an array of 100 int elements
The struct also contains string word
There is an array of datatype wordBlock
There are a total of two thousand possible elements
I must count the words
Count the number of bytes
And count the number of lines
I must also determine what words appear on which line number
I must output each unique word only once and list its corresponding line number
The words This and this and THIS would all be unique words
我无法解决的大问题是如何只输出每个单词一次以及它在哪一行。一个词可能存在于多行,我只需要这个词一次及其对应的行号。我不想每次调用 block[n].word 时都显示相同的词。我也不打算计算这个词在代码中出现的次数,只计算包含它的行号。
这是我的代码:
#include "main.h"
using namespace std;
typedef struct
{
string word;
array<int, 100> lines;
} wordBlock;
int main()
{
string wordBuf("");
istringstream wordGather("");
string buffer("");
int numberOfLines = 0;
int numberOfBytes = 0;
int wordCount = 0;
int idxCount = 0;
while (getline(cin, wordBuf))
{
numberOfBytes = numberOfBytes + (wordBuf.length() + 1);
numberOfLines++;
wordGather.str(wordBuf);
wordGather.clear();
while (wordGather >> buffer)
{
wordCount++;
block[idxCount].word = buffer;
idxCount++;
for (auto indexCount = 0; indexCount < 100; indexCount++)
{
block[idxCount].lines[indexCount] = numberOfLines;
}
}
}
cout << "There are " << wordCount << " words, " << numberOfLines
<< " lines, and " << numberOfBytes << " bytes." << endl;
for (auto idxCount = 0; idxCount < block.size(); idxCount++)
{
for (auto index = 0; index < block.size(); index++)
{
for (auto lineIdx = 1; lineIdx < 2; lineIdx++)
{
if (block[idxCount].word == block[index].word)
{
block[idxCount].lines[lineIdx] = block[index].lines[0];
}
}
}
}
return 0;
}
预先感谢您提供任何可能的建议。
最佳答案
您将需要一张包含行号列表的 map ,
map<string, vector<int>> words;
然后,您需要用代码(根据您的代码修改)填充它:
while(wordGather >> buffer)
{
wordCount++;
if(words.find(buffer) == words.end())
words[buffer] = std::vector<int>();
words[buffer].push_back(numberOfLines);
}
您可以使用类似以下内容显示单词列表和行号:
for(auto word:words)
{
cout << word.first << " at lines";
for(auto line:words.second)
cout << " " << line;
cout << endl;
}
关于c++ - 无法围绕单个单词的输出及其相应的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35903904/