简单的C++函数
simple C++ functions
好吧,所以我确信我在做一些愚蠢的事情: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)
您不恰当地混合了整数和无符号长字符。wordCount
和a
变量以及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;
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗