USE OF CHAR STRING POINTER

Write your question here. How do I put something into the character string array s?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// testStrings and Pointers
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;

int main()
{
	char* s;


	printf("Enter a sentence: ");
	cin >> *s;

	printf("The sentence entered is %c characters long.\n", strlen(s));
	return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstring>

int main()
{
    char str[100];

    std::cout << "Enter a sentence: ";
    std::cin.getline(str, 100);

    std::cout << "The sentence entered is " << std::strlen(str) << " characters long.\n";
}

Though you should really use std::string whenever possible:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main()
{
    std::string str;

    std::cout << "Enter a sentence: ";
    std::getline(std::cin, str);

    std::cout << "The sentence entered is " << str.size() << " characters long.\n";
}
Thank you for responding. As part of my learning exercise, I went through the above two examples you provided. For the particular problem I submitted, I want to use a char pointer to point to an array containing the character string entered after the prompt "Enter a sentence". I am bewildered on how to do this.
How do I get p_c_test to point to str?


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
27
28
29
30
31
32
33
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;

int main()
{
	char* p_c_test;
	char str[100];
	
//	string str;

	printf("Enter a string: ");
	cin.getline(str, 100);
	
	cout << "This is str after getline: " << str << endl;
	// How do I get p_c_test to point to str?
        p_c_test = &str;
	int strLength = strlen(str);
	cout << "str's length is : " << strLength << endl;




//	cout << "This is what p_c_test is pointing at: " << *p_c_test << endl;
//      p_c_test is pointing at the first character of the character string str.



//	printf("The string entered is %u characters long.\n", (unsigned)strlen(str));
	return 0;
}

p_c_test = str; should do it.
Thank you very much. I cleaned up my code and this is what it looks like. It works.

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
27
28
29
30
// testStrings and Pointers
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;

int main()
{
	char* p_c_test;
	char str[256];
	p_c_test = str;	

	printf("Enter a sentence: ");
	cin.getline(str, 256);
	
	cout << "str's length is : " << strlen(str) << endl;

// Using pointer
	for (int i = 0, n = strlen(str); i <= n; i++)
	{
		cout << *(p_c_test + i);
	}
	cout << endl;
return 0;
}




You can also use str directly for that:
1
2
3
4
for (int i = 0, n = strlen(str); i < n; ++i)
{
    cout << *(str + i);
}
Topic archived. No new replies allowed.