Help with the char function

I must write a program that tells the user how many characters are in the string that they entered. But my pointer is giving me an error, telling me that it is equal to nullptr.

Here is my code:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int countChars(int*);
int *strPtr = nullptr;
string word;
int main()
{
countChars(strPtr);
cout << "That string has " << *strPtr << " characters in it.";
cin.get();
}
int countChars(int *strPtr)
{
string word;
cout << "Enter a string: ";
cin >> word;

*strPtr = word.length();

return *strPtr;
}
Last edited on
You don't need to mess around with pointers for this. Just return the value.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;

int getWordAndCountChars();

int main()
{
  int number_of_letter = getWordAndCountChars();
  cout << "That string has " << number_of_letter<< " characters in it.";
  cin.get();
}

int getWordAndCountChars()
{
  string word;
  cout << "Enter a string: ";
  cin >> word;
  return word.length();
}
Last edited on
I understand... But my homework requires that I do.
Now with pointer use.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;

void getWordAndCountChars(int* number);

int main()
{

  int number_of_letter;
  getWordAndCountChars(&number_of_letter);

  cout << "That string has " << number_of_letter<< " characters in it.";
  cin.get();
}

void getWordAndCountChars(int* number)
{
  string word;
  cout << "Enter a string: ";
  cin >> word;
  *number = word.length();
}
Last edited on
Topic archived. No new replies allowed.