Code compiles in main.cpp, but not in header.
Jun 7, 2017 at 7:39pm UTC
If I paste this code into my main.cpp it'll compile and do what it's supposed to do just fine.
If I put it in a header, I get an error on the third line that says "error: 'string' does not name a type"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#ifndef NAME
#define NAME
#include <iostream>
#include <string>
std::string getNameInput()
{
using std::string;
string your_name;
std::cout << "Enter your name." <<
std::endl;
std::getline(std::cin, your_name);
return your_name;
}
#endif
Jun 7, 2017 at 8:47pm UTC
Example 1 (correct):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#ifndef NAME
#define NAME
#include <iostream>
#include <string>
std::string getNameInput();
int main()
{
std::string str = getNameInput();
return 0;
}
std::string getNameInput()
{
using std::string;
string your_name;
std::cout << "Enter your name: " ;
std::getline(std::cin, your_name);
return your_name;
}
#endif // NAME
Compilation command:
g++ -std=gnu++14 -Wall -Wextra -pedantic-errors -pipe -O3 main.cpp -o main.exe
Output:
- - -
Example 2 (wrong):
main.cpp
1 2 3 4 5 6 7 8 9 10
#include <iostream>
#include <string>
#include "name.h"
int main()
{
using std::string;
std::string str = getNameInput();
return 0;
}
name.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#ifndef NAME
#define NAME
#include <string>
std::string getNameInput()
{
using std::string;
string your_name;
std::cout << "Enter your name: " ;
std::getline(std::cin, your_name);
return your_name;
}
#endif // NAME
Compilation command:
g++ -std=gnu++14 -Wall -Wextra -pedantic-errors -pipe -O3 main.cpp -o main.exe
Output:
- - -
Example 3 (correct):
main.cpp
1 2 3 4 5 6 7 8 9 10
#include <iostream>
#include <string>
#include "name.h"
int main()
{
using std::string;
std::string str = getNameInput();
return 0;
}
name.h:
1 2 3 4 5 6 7 8 9 10
#ifndef NAME
#define NAME
#include <string>
std::string getNameInput();
#endif // NAME
name.cpp
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include "name.h"
std::string getNameInput()
{
using std::string;
string your_name;
std::cout << "Enter your name: " ;
std::getline(std::cin, your_name);
return your_name;
}
Compilation command:
g++ -std=gnu++14 -Wall -Wextra -pedantic-errors -pipe -O3 main.cpp name.cpp -o main.exe
Output:
Could you please try to explain better your issue?
Topic archived. No new replies allowed.