簡體   English   中英

C ++如何讀取文件,將每個單詞轉換為小寫,然后引用每個單詞?

[英]C++ How do I read in a file, convert each word to lower case and then cout each word?

我在開始程序時遇到麻煩。 我需要從文件中讀取每個單詞,然后將其轉換為小寫。 我想在找到每個單詞后std :: cout每個單詞。 我假設我需要以某種方式使用Cstr()。 我猜我應該使用類似

ofs.open(infile.c_str());

但是如何小寫呢?

string[i] = tolower(string[i]);

然后,

std::cout << string[i];

謝謝您的幫助。

這是一個完整的解決方案:

#include <ctype.h>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <iostream>

char my_tolower(unsigned char c)
{
    return tolower(c);
}

int main(int ac, char* av[]) {
    std::transform(std::istreambuf_iterator<char>(
        ac == 1? std::cin.rdbuf(): std::ifstream(av[1]).rdbuf()),
        std::istreambuf_iterator<char>(),
        std::ostreambuf_iterator<char>(std::cout), &my_tolower);
}
int main()
{

    ofstream of("xyz.txt");

    clrscr();
    ifstream inf;
    char line;
    inf.open("abc.txt");
    int count=0;
    while(!inf.eof())
    {
        inf.get(line);
        if(line>=65 && line<=123)
        {
            cout<<line;
            line=line-32;
            of<<line;
            count++;
            cout<<line;
        }
    }
    cout<<count;
    getch();
    return 0;
}

我找到了自己問題的答案。 我真的不想使用轉換,但是也可以使用。 如果還有其他人偶然發現這是我想出的方法...

#include <iostream>
#include <string>
#include <fstream>

int main()
{
std::ifstream theFile;
theFile.open("test.txt");
std::string theLine;
while (!theFile.eof())
{
  theFile >> theLine;       
  for (size_t j=0; j< theLine.length(); ++j)
  {
    theLine[j] = tolower(theLine[j]);
  }
  std::cout<<theLine<<std::endl;
     } 

 return 0;
}

首先,除非這類似於家庭作業,否則一次處理一個字符比一次處理一個單詞可能更容易。

是的,您有將小寫轉換為小寫的正確想法,通常,您需要在將輸入傳遞給tolower之前將輸入轉換為unsigned char的次要細節。

就個人而言,我會避免進行顯式的輸入和輸出,而是使用一對istream_iterator和一個ostream_iterator進行std::transform以獲得結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM