简单的C++函数

simple C++ functions

本文关键字:函数 C++ 简单      更新时间:2023-10-16

好吧,所以我确信我在做一些愚蠢的事情:D

我有一个功能:

int wordFunc(string a){
    std::ifstream inp;
    inp.open(a, std::ios::in);
    if (inp.is_open()){
        std::string word;
        unsigned long wordCount = 0;
        while(!inp.eof()){
            inp >> word;
            while(word.length() > 0){
                wordCount++;
            }
            inp.close();
        }
        return wordCount;
    }
}

该字符串是一个用户输入文件.txt-它现在设置为C:\Dump\user.txt

当我用调用代码时

int main(){
    string file;
    int words = 0;
    file = "C:\Dump\user.txt";
    int a = wordFunc(file, words);
    cout << "Words: " << a << endl;
    return 0;
}

控制台就停了——我已经很多年没有用C++编码过任何东西了,所以我肯定很生疏了——有什么帮助吗?

编辑在某种灵魂的帮助下,我最终变成了这个

unsigned long wordFunc(const std::string& a){
    std::ifstream inp(a);
    system("cls");
    unsigned long wordCount = 0;
    std::string word;
    while(inp >> word)
    {
        wordCount++;
    }
    return wordCount;
}

对于函数-应该发布更新

您的问题是:

        while(word.length() > 0){
            wordCount++;
        }

这将永远循环。你可能是指

        if(word.length() > 0){
            wordCount++;
        }

您有很多问题。


正如另一位海报所评论的那样,这句话是:

while (word.length() > 0)

将永远循环,您需要将其更改为:

if (word.length() > 0)

您不恰当地混合了整数和无符号长字符。wordCounta变量以及wordFunc()的返回值应该相同。


inp.close()位于读取循环内部,而不是位于它所属的外部。这意味着它将在处理完第一行之后关闭文件。


if语句中还有return语句,这意味着您有语法错误,在一个执行路径(无法打开文件的路径)中没有返回任何内容。

您需要交换return和它后面的右大括号。

这也意味着wordCount变量也必须在if语句之外声明(在函数的顶层)。


我认为fstream::open()采用char*而不是字符串,所以您应该将其重新编码为:

inp.open (a.c_str(), std::ios::in);

您对具有两个参数的wordFunc()的调用与只有一个参数的原型不匹配。


有一些无关的变量,例如main()中的words


最后一个字被计数两次,因为只有当您试图读取超过文件末尾时才会设置EOF标志。您可以通过对if语句的简单修改来修复此问题,该语句递增wordCount:

if ((!inp.eof()) && (word.length() > 0)) {

做了所有这些改变,你最终会得到:

#include <iostream>
#include <fstream>
unsigned long wordFunc (std::string str) {
    unsigned long wordCount = 0;
    std::ifstream inp;
    inp.open(str.c_str(), std::ios::in);
    if (inp.is_open()) {
        std::string word;
        while (!inp.eof()) {
            inp >> word;
            if ((!inp.eof()) && (word.length() > 0)) {
                wordCount++;
            }
        }
        inp.close();
    }
    return wordCount;
}
int main() {
    std::string file;
    file = "user.txt";
    unsigned long a = wordFunc(file);
    std::cout << "Words: " << a << std::endl;
    return 0;
}

C++在标准库中已经有了一些函数来完成您想要的大部分工作,所以您可以执行以下操作:

#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
int main() { 
    std::ifstream in("user.txt");
    std::cout << "Words: " 
              << std::distance(std::istream_iterator<std::string>(in),
                               std::istream_iterator<std::string>());
    return 0;
}

我喜欢三个可执行语句需要五个标题的代码!

如果你坚持自己计数,我会做一些类似的事情:

std::ifstream in("user.txt");
std::string word;
while (in >> word)
    ++wordCount;
std::cout << "Words: " << wordCount;