gpt4 book ai didi

c++ - 另一个函数的输出

转载 作者:行者123 更新时间:2023-11-28 06:01:35 24 4
gpt4 key购买 nike

在我的 C++ 项目中,我有 3 个文件,分别是 main.cpp、functions.cpp 和 functions.h。

函数.cpp:

#include <functions.h>

using namespace std;

int ascii(string text)
{
vector<int> tab;

for( int i=0; i<text.length(); i++ )
{
char x = text.at(i);
tab.push_back(x);
}

for(int k=0; k<tab.size(); k++)
{
cout << tab[k] << endl;
}
}

函数.h:

#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED

#include <iostream>
#include <string>
#include <vector>

int ascii(std::string text);

#endif // FUNCTIONS_H_INCLUDED

主要.cpp:

#include <functions.h>

using namespace std;

int main()
{
string plaintext;
cout << "Enter text : ";
ws(cin);
getline(cin, plaintext);

ascii(plaintext);

return 0;
}

如您所见,值存储在 functions.cpp 文件中的数组中。

如何将数组从 functions.cpp“移动”到 main.cpp 以便我可以操作这些数据?

最佳答案

一种方法是执行以下操作

函数.cpp

using namespace std;

vector<int> ascii(string text) // original: int ascii(string text)
{
vector<int> tab;

for( int i=0; i<text.length(); i++ )
{
char x = text.at(i);
tab.push_back(x);
}

for(int k=0; k<tab.size(); k++)
{
cout << tab[k] << endl;
}

return tab; // original: no return
}

函数.h

#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED

#include <iostream>
#include <string>
#include <vector>

std::vector<int> ascii(std::string text); // original int ascii(std::string text)

#endif // FUNCTIONS_H_INCLUDED

主要.cpp

#include <functions.h>

using namespace std;

int main()
{
string plaintext;
cout << "Enter text : ";
ws(cin);
getline(cin, plaintext);

vector<int> returning = ascii(plaintext); // original: ascii(plaintext)

return 0;
}

关于c++ - 另一个函数的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33182004/

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