[英]Read text file with different number of words in each line into two dimensional array in C++
[英]Count words in each line of text file in c++
我使用argc,argv和getline打開一個txt文件。 我已經正確地做到了,但是現在我必須獲得每行的單詞數(以前不知道行數),並且必須反向輸出它們。 從底線到頂線的含義。 任何幫助表示贊賞。 此代碼輸出文件中的單詞數:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
{
if(argc < 1){
cerr << "Usage: " << argv[0] << "filename.txt" << endl;
}
ifstream ifile(argv[1]);
if(ifile.fail()){
cerr << "Could not open file." << endl;
return 1;
}
int n;
ifile >> n;
cout << n;
int numberOfWords = 0;
string line;
for(int i = 0; i <= n; i++){
getline(ifile, line);
cout << line << endl;
}
size_t i;
if (isalpha(line[0])) {
numberOfWords++;
}
for (i = 1; i < line.length(); i++) {
if ((isalpha(line[i])) && (!isalpha(line[i-1]))) {
numberOfWords++;
}
}
cout<<"The number of words in the line is : "<<numberOfWords<<endl;
return 0;
}
要查找每行的單詞數,您可以使用std::getline()
遍歷每行,並使用std::stringstream
提取每個由空格分隔的輸入塊。 然后,您將遍歷每個輸入塊,並檢查每個字符是否為字母:
int numberOfWords = 0;
for (std::string line, word; std::getline(ifile, line); )
{
std::istringstream iss(line);
while (iss >> word)
{
bool alpha = true;
for (char c : word)
if (!std::isalpha(c)) alpha = false;
if (alpha) ++numberOfWords;
}
std::cout << "Number of words on this line: " << numberOfWords << std::endl;
numberOfWords = 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.