Welcome to HBH! If you had an account on hellboundhacker.org you will need to reset your password using the Lost Password system before you will be able to login.

Help with inputting strings into arrays in c++?


ghost's Avatar
0 0

I want to be able to receive string input from a user and store it in a way that will allow me to operate with individual characters in the string. An array was my first thought but that does not allow me to put spaces in. The other option was a string using getline() to allow for spaces but this does not allow me to operate with individual characters. Any help would be appreciated. Thanks.


yours31f's Avatar
Retired
10 0

Stings are arrays

string example = "This is a string.";

cout << example[6] 


markupi


ghost's Avatar
0 0

yours31f wrote: Stings are arrays

string example = "This is a string.";

cout << example[6] 


markupi

Like he said, they are arrays.. so you just need a simple for loop

#include <iostream>
#include <string>

using namespace std;

int main(){
    string test;
    test = "Whatever the string is to say";

    int i;
    char c;
    for (i=0;i <= len(test);i++){
        // do whatever you need to the char
        c = test[i];
        }
    return 0;
    }

[Edit] Just found a useful little site for compiling C/C++. Useful for checking quick scripts if you're on a public computer or whatever. http://www.comeaucomputing.com/tryitout/


ynori7's Avatar
Future Emperor of Earth
0 0

Here are the two best ways that I see for you to approach this:

#include<string>
#include<cstdio>
using namespace std;

char changeChar(char);

int main()
{
  string test;
  getline(cin, test);
  cout<<test[1]<<endl;
  test[1]='a';
  cout<<test<<endl;

  char input[255];
  fgets(input, 255, stdin);
  cout<<input[1]<<endl;
  input[1]='a';
  cout<<input<<endl;
}```
Both methods should have the same output.

ghost's Avatar
0 0

Ok, I feel like a bit of an idiot now. Thanks guys.