Why aren't strings allowed in structures?

Started by
5 comments, last by alvaro 11 years, 9 months ago
Why aren't strings allowed in a structure. The only way a string is permitted in a structure is if this notation is used == std:: string random_var:

struct example
{
std::string random_var;
};

int main()
{

cout << "Enter name:" << endl;
cin >> company.random_var;
}

however the compiler doesn't allow user input for this object . Why is that?

I hope this is the right section for this question.
Advertisement
What is company? You don't declare it anywhere.

Try adding:
example company;

Above your cout statement.

Works for me:
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::string;

struct testExample
{
string random_string;
};

int main()
{
testExample company;
cout << "Enter the name: ";
cin >> company.random_string;
cout << company.random_string;
return 0;
}
Sorry my mistake: that was a random example I made up. But my current program doesn't allow strings in my structure it says its undefined


#include <iostream>
#include <String>

using namespace std;

struct Pizza
{
String company_name;
int diameter;
double weight;

};

int main()
{
Pizza costumer;

cout << "Which Pizza compnay do you order from?" << endl;
cin >> costumer.company_name;

cout << " " << endl;

cout << "You order from: " << costumer.company_name << endl;

cout << " " << endl;

cout << "What is your desired size of Pizza (Diameter)?" << endl;
cin >> costumer.diameter;

cout << " " << endl;

cout << "Your favorite size, in terms of diameter is " << costumer.diameter << " inches" << endl;

cout << " " << endl;

cout << "Normally what is the weight of your pizza? " << endl;
cin >> costumer.weight;

cout << " " << endl;

cout << "Your pizza weight is normally " << costumer.weight << endl;


system("Pause");
return 0;

}
C++ is case sensitive. string is not the same as String.
Try using a lowercase "string". Capital "String" gives an error.

As for the errors I get these:
test.cpp:8: error: `String' does not name a type
test.cpp: In function `int main()':
test.cpp:19: error: 'struct Pizza' has no member named 'company_name'
test.cpp:23: error: 'struct Pizza' has no member named 'company_name'

I'm assuming you were referring to bottom two as the issue. The top one is the one to look out for showing something is amiss in the struct code. Top to bottom is the way I usually have to fix errors because the top ones tend to create the ones further down.
Oh I see, thank you very much all of you!
Please, post this kind of question in "For Beginners".

This topic is closed to new replies.

Advertisement