gpt4 book ai didi

C++ : Error using argv[1] into a function to read a . txt 文件

转载 作者:行者123 更新时间:2023-11-27 23:57:58 24 4
gpt4 key购买 nike

我目前正在开始使用 C++ 并尝试创建一个函数,该函数可以打开 .txt 文件、读取它并将其单词保存在数组中(每个单词都是一个蛋白质序列)。不幸的是,我在函数中调用包含文件名 (argv[1]) 的参数没有成功。任何人都可以发现我的代码中的错误或我实现此代码的方式中的错误吗?提前致谢,您将在下面找到代码和错误消息:

图书馆

这是我的库和“快捷方式”。

// Librairies
#include <iostream>
#include <string>
#include <fstream>

// Alias
using std::cout;
using std::endl;
using std::string;

函数

现在这是函数,请注意文件名应该是一个包含 argv[1](执行时指定的 .txt 文件的名称)的字符串:

string SequenceChoice(int n, string filename); // Function returning a string

std::ifstream sequenceFile (filename); //Opens the file specified on execution

if ( sequenceFile.is_open() )
{
cout<<"File opened"<<endl;

string tmp;
int i = 0;

while( sequenceFile >> tmp ) // Counts the number of sequences (words)
{
i++;
}

string allchains[i]; // Creates an array of strings, to save all the words

sequenceFile.clear();
sequenceFile.seekg(0, sequenceFile.beg); // Replaces the cursor at the beginning of the file
i=0;

while( sequenceFile >> allchains[i]) // Saves each word as a string in an array
{
cout << allchains[i] << tmp;
i++;
}

sequenceFile.close();
cout<< "File closed"<<endl;
}

else
{
cout << "Error: Cannot open file" << endl;
}

return allchains[n]; // returns the 'n'th word (n being specified when calling the function


// end of the function

主要内容

现在是主要功能,我不确定执行 string filename = argv[1] 是否有效,但是当我保留这一步而不是放置 argv[1] 时,我得到的错误更少] 作为我的 SequenceChoice() 函数的参数。

int main(int argc, char *argv[]) {

if(argc >= 2)
{
string filename = argv[1];
cout << SequenceChoice( 2, filename ) << endl; // I expect it to give me the 3rd word of a .txt file for example.
}
else
{
cout << "Error : No file" << endl;
}


return 0;
}

我得到的错误信息

Error message

上面的链接是我在编译时收到的错误消息的图片,我在互联网上搜索了几个小时如何解决这个问题,不幸的是我无法让代码正常工作。我处理 argv[] 的方式可能存在类型错误,但我未能解决它,因此非常感谢任何帮助和评论。

最佳答案

请尝试更改以下行

string SequenceChoice(int n, string filename); // Function returning a string

string SequenceChoice(int n, string filename) { // Function returning a string

您正在尝试编写一个函数,但是 ;正在终止你的功能, body 没有开始。它应该工作。也请仔细阅读一本书。

This page列出了适合所有经验水平的非常好的书籍。

关于C++ : Error using argv[1] into a function to read a . txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41200861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com