在我的C ++项目中,我有3个文件,分别是main.cpp,functions.cpp和functions.h。
functions.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;
}
}
functions.h:
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
#include <iostream>
#include <string>
#include <vector>
int ascii(std::string text);
#endif // FUNCTIONS_H_INCLUDED
main.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,以便我可以操作这些数据?
答案 0 :(得分:1)
一种方法是做以下
functions.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
}
functions.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
的main.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;
}