string

Hello

i want to know how can i save the following sentence in just one variable.

hello how are you

i've tried with scanf but ot only save the first word (hello)
Well, if you can use C++, you can use getline() and an std::string...You could also try using %s with scanf(), although this can cause a buffer overflow if the user types in too many letters. I *think* %##s will only accept ## characters, but I don't remember exactly.
thanks so much.. it works as i expect...
Sigh.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <string.h>

int main()
  {
  char name[ 100 ];
  int  len;

  printf( "Please enter your full name> " );

  fgets( name, 100, stdin );
  len = strlen( name );
  if (name[ len - 1 ] == '\n')
    name[ len -= 1 ] = '\0';

  printf( "Your name, \"%s\", is %d characters long.\n", name, len );

  return 0;
  }

http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

Hope this helps.


you can use gets to to stored hellow how are you

#include <stdio.h>

int main()
{
char name[ 100 ];

printf( "Please enter your full name> " );

gets( name );

printf( "Your name, %s is ", name );

return 0;
}

it also run try it.
Ack! Are you trying to make unsafe, buggy software?

Never, never, never use gets() !

http://www.gidnetwork.com/b-56.html


If you want something more gets()- or std::getline()-like then read here
http://www.cplusplus.com/forum/beginner/4174/page1.html#msg18271
Why doesn't this work
It should printout a message when i type "who are you" but It doesn't
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
int main()
{
	using namespace std;

	char sentence[20];
	cin.get(sentence,19);
	if (sentance == "who are you")
		cout << "I am you\n";
	else
		cout << "Error\n";
	return 0;
}
Last edited on
What!? Git yer own thread.




On line 8 you are comparing pointers to char arrays; you are not comparing strings. Presuming there is a good reason you aren't using std::string, you can compare it with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstring>
int main()
{
	using namespace std;

	char sentance[20];
	cin.get(sentance,19);
	if (strcmp( sentance, "who are you" ) == 0)
		cout << "I am you\n";
	else
		cout << "Error\n";
	return 0;
}

However, you are better off just #including <string> and using either:

8 if (string( sentance ) == "who are you")

or:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
int main()
{
	using namespace std;

	string sentance;
	getline( cin, sentance );
	if (sentance == "who are you")
		cout << "I am you\n";
	else
		cout << "Error\n";
	return 0;
}

Hope this helps.
Topic archived. No new replies allowed.