1.

Solve : C++ Strings, headers and noob.?

Answer»

Hello all,

I am currently trying to figure out how to set a variable as a string, write to it, and DISPLAY it on command. I realize this will mosty likely involve an array, however I seem to be getting lost in the headers. Whenever I try to compile I get the following error.  Code: [Select]test_1.cpp(18): error C2872: 'string' : ambiguous symbol If I remove the line Code: [Select]using namespace std; and add std:: in front of all the cins and couts then it will work. So my question is, how can I achieve this without having to remove the namespace std, and without having to add std:: in front of the iostreams. Here is my source:

Code: [Select]
#include "stdafx.h"
#include <iostream&GT;

//which header is for strings?!
#include <fstream>
#include <xstring>

using namespace std;

char string[50];


int main()
{
cout << "Hello you crazy world.\n";
cin >>string[50];

cout<<"Your full name is "<<string[50]<<"\n";

system("pause");


return 0;
}

I have also tried removing the headers I have shown in my source, one by one, to no avail.

Thanks in advance. I will gladly supply more information if I was too vague in my explanation. the string class is defined in "string.h". Also note that the string headers do nothing for "psuedo" strings, (or char arrays). the proper "C++" way would be:


Code: [Select]#include <iostream>
#include <string>
using namespace std;


void main()
{
        int tempkey;
string* getstring = new string("");

cin >> *getstring;
cout << *getstring;
free(getstring);

cout << "complete. Press Ctrl-Z to exit.";

cin >> tempkey;


}


Using STANDARD C code to get data into a char array is possible as WELL:

Code: [Select]#include <STDLIB>
void main()
{
char* grabstring;
grabstring = (char*)malloc(50);
gets(grabstring);
printf("%s",grabstring);

free(grabstring);
}

your main problem is from naming a variable "string" which undoubtedly conflicts with a "string" type defined elsewhere (such as the include which goes unused alongside fstream). Also you are using cin and directing the input directly to the last element of the array, so unless the user only enters a single character, you will get a buffer overflow.I was able to achieve this with the following code:

Code: [Select]
#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

string name ="";


int main()
{

   cout << "Please enter your name.\n";

   cin >> name;

   cout << "Your name is "<< name << endl;

   system("PAUSE");

return 0;

}

Thanks anyhow, I would have tried your suggestions but I am not familiar enough with the language yet for those functions. In time....



Discussion

No Comment Found