在fstream C ++中读取新行字符

时间:2017-12-12 03:02:05

标签: c++

如何阅读新行字符?我正在尝试进行字符计数,但新行阻碍了。我尝试了if (text[i] == ' ' && text[i] == '\n')但是没有用。 Here is my repl.it session

我试图从file.txt中读取这个:

i like cats
dogs are also cool
so are orangutans

这是我的代码:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream input;
    input.open("file.txt");

    int numOfWords = 0;

    while (true)
    {
        string text;
        getline(input, text);

        for(int i = 0; i < text.length(); i++)
        {
            if (text[i] == ' ') 
            {
                numOfWords++;
            }
        }

        if (input.fail())
        {
            break;
        }
    }
    cout << "Number of words: " << numOfWords+1 << endl;
    input.close();
}

1 个答案:

答案 0 :(得分:1)

您的问题是询问如何计算字符,但您的代码正在计算字词#build net = tf.input_data(shape=[None, 64, 17]) net = tf.lstm(net, 128, dropout=[.2,.8], return_seq=True) net = tf.lstm(net, 128, dropout=[.2,.8], return_seq=True) net = tf.lstm(net, 128, dropout=[.2,.8]) net = tf.fully_connected(net, 3, activation='softmax') net = tf.regression(net, optimizer='adam', learning_rate=0.01, loss='categorical_crossentropy') #train model = tf.DNN(net, tensorboard_verbose=0) model.fit(trainX, trainY, validation_set=(testX,testY), show_metric=True, batch_size=None) 吞下换行符。如果要计算单词,则无需担心它们。实际上,在这种情况下,您可以使用std::getline()来大大简化计数,例如:

operator>>

如果你真的想要计算字符而不是,请使用std::ifstream::get()一次读取文件1个字符,例如:

int main()
{
    ifstream input("file.txt");

    int numOfWords = 0;
    string word;

    while (input >> word)
        ++numOfWords;

    cout << "Number of words: " << numOfWords << endl;

    return 0;
}
相关问题