help with string/char array (newb)

This is a discussion on help with string/char array (newb) within the C++ Programming forums, part of the General Programming Boards category; i am trying to make a very basic c++ program, using msvc++ 6 for my program i need the user ...

  1. #1
    They Call me Mister Sako
    Join Date
    Jul 2004
    Posts
    169

    help with string/char array (newb)

    i am trying to make a very basic c++ program, using msvc++ 6

    for my program i need the user to input a string, which is an array of characters right? ( am using an arrya of char now instead of strin since doing this with a string is more complicated apparently?) well i need to be able to pick out specific characters of what the user writes

    Code:
    #include <iostream>
    #include <string>
    #include <stdlib.h> 
    
    using namespace std;
    
    int main()
    {
    	char input[100];
    
    	cout << "Input a word or phrase" << endl;
    	cin >> input;
    	
    
    	cout << "test: " << input[3];
    	
    
    	return (0);
    }
    lets say for input i put "abc" i want to write out c which is the third char of input.

    whats happeneing is its prinitng out NOTHING, it has test: (blank)

    what am i doing wrong?
    AIM: MisterSako | MSN: sakotheinsane@hotmail.com | E-mail: klinerr1@nc.rr.com
    The goal of computer science is to be lazy

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    am using an arrya of char now instead of strin since doing this with a string is more complicated apparently?
    In what computer language is using a string type more complicated?

    input[3]

    lets say for input i put "abc" i want to write out c which is the third char of input.
    What index value do arrays start at? Write down the first 5 index values of an array. What is the index value of the third element?
    Last edited by 7stud; 05-25-2005 at 02:16 AM.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    nvm 7stud beat me too it.
    Last edited by Quantum1024; 05-25-2005 at 02:20 AM.

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    Using a string is just as easy as using a character array, although there may be some considerations you would not need when using a character array (such as making sure there actually are at least 3 characters in the string before you attempt to output the third character).

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        string input;
    
        cout << "Input a word or phrase" << endl;
        cin >> input;
    	
        if( input.length() >= 3 )
            cout << "test: " << input[2];  // input[2] is the third character
    	
        return 0;
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    They Call me Mister Sako
    Join Date
    Jul 2004
    Posts
    169
    ohhh the array starts with [0], my mistake

    and i was reading something on another post in which a guy was trying to get the length of a string and it seemed like he was trying to do something complicated, i guess i can just use the length() function
    AIM: MisterSako | MSN: sakotheinsane@hotmail.com | E-mail: klinerr1@nc.rr.com
    The goal of computer science is to be lazy

  6. #6
    They Call me Mister Sako
    Join Date
    Jul 2004
    Posts
    169
    ok im having some more trouble, i really cant figure this out, this time its with If statements, im 99% sure i did everything correctly and i got all my semicolons, heres the code

    Code:
    #include <iostream>
    #include <string>
    #include <stdlib.h> 
    #include <cstdlib>
    
    using namespace std;
    
    string scramblePhrase(string input);
    string scrambleWord(string words, int x);
    
    
    int main()
    {
    	string input;
    	string words[50];
    	int wordslen[50];
    	int y,x;
    	int spaces[50];
    
    
    	cout << "Input a word or phrase: ";
    	cin >> input;
    	
    	x=0;
    	for (y=0; y<=input.length()-1; y++;)
    	{
    		If (input[y]!=" ")
    		{
    			words[x][y]=input[y];
    		} else
    		{
    			spaces[x]=y;
    			wordslen[x]=words[x].length();			
    			x++;
    		}	
    	}
    
    
    
    	cout << "words[0]: " << words[0] << endl;
    	cout << "wordslen[0]: " << wordslen[0] << endl << endl;
    
    	cout << "words[1]: " << words[1] << endl;
    	cout << "wordslen[1]: " << wordslen[1] << endl;
    
    	return 0;
    }
    
    
    string scramblePhrase(string input)
    {
      
    	return input;
    }
    
    string scrambleWord(string words, int x)
    {
    	return words;
    }
    and heres the errors im getting
    -------------------Configuration: Mystterio Project - Win32 Debug--------------------
    Compiling...
    main.cpp
    C:\Program Files\Microsoft Visual Studio\MyProjects\Mystterio Project\main.cpp(25) : error C2059: syntax error : ';'
    C:\Program Files\Microsoft Visual Studio\MyProjects\Mystterio Project\main.cpp(27) : error C2065: 'If' : undeclared identifier
    C:\Program Files\Microsoft Visual Studio\MyProjects\Mystterio Project\main.cpp(27) : error C2446: '!=' : no conversion from 'char *' to 'int'
    This conversion requires a reinterpret_cast, a C-style cast or function-style cast
    C:\Program Files\Microsoft Visual Studio\MyProjects\Mystterio Project\main.cpp(27) : error C2040: '!=' : 'int' differs in levels of indirection from 'char [2]'
    C:\Program Files\Microsoft Visual Studio\MyProjects\Mystterio Project\main.cpp(28) : error C2143: syntax error : missing ';' before '{'
    C:\Program Files\Microsoft Visual Studio\MyProjects\Mystterio Project\main.cpp(30) : error C2181: illegal else without matching if
    Error executing cl.exe.

    Mystterio Project.exe - 6 error(s), 0 warning(s)
    Last edited by MisterSako; 05-25-2005 at 10:56 AM.
    AIM: MisterSako | MSN: sakotheinsane@hotmail.com | E-mail: klinerr1@nc.rr.com
    The goal of computer science is to be lazy

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    Look at each error. You have an extra semi-colon ';' at the end of your for statement. You capitalized the i in "If", it should be lower case (case matters in C++). Fix those first then recompile and see what is left.

    BTW, when comparing a character in a string to see if it is not a space, you should compare it against a character literal like ' ' instead of a string literal like " ". The double quotes signify a string of characters instead of a single one.

  8. #8
    They Call me Mister Sako
    Join Date
    Jul 2004
    Posts
    169
    ok taking out the semi colon and fixing the If to if fixed the errors, i dont understand what you're saying about looking to see if the character in the string doesn't have a space

    edit: i replaced the " with ' in the if statement. but when i compile when it gets to the part where the loop starts i get a Winxp error that makes the program close (the kind that asks if you want to send error report or dont send)
    Last edited by MisterSako; 05-25-2005 at 11:54 AM.
    AIM: MisterSako | MSN: sakotheinsane@hotmail.com | E-mail: klinerr1@nc.rr.com
    The goal of computer science is to be lazy

  9. #9
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    Code:
    string input;
    
    cout << "Input a word or phrase: ";
    cin >> input;
    When getting an input string using the stream extraction operator (>>) extraction will stop at the first whitespace, i.e. tab/newline/space. This means that input will only ever have a single word in it which likely throws the whole reason for having the for loop below it in the garbage. If you want to get and store multiple words from the user you will need to go another route.

    There is also little purpose to storing the lengths of the words in a seperate array, since the value stored in wordslen[X] is supposed to be equal to words[X].length(), just use words[X].length() where you need it instead of wasting space.

    Code:
    words[x][y]=input[y];
    Code like the above holds a hidden danger for newbs (and I bet the reason for your little crash). The strings stored in the words array have no storage allocated for them to hold any data. What you are doing above is attempting to set a character at an index which does not exist. A suggested method you could use to get around that is as follows:

    Code:
    words[x] += input[y];
    The above causes the string identified by words[x] to allocate memory for an additional character and copies the character to the newly allocated slot in memory. Of course, your whole loop really needs to be reworked and this bit of code is likely unnecessary.
    Last edited by hk_mp5kpdw; 05-25-2005 at 12:05 PM.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  10. #10
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    You appear to be trying to isolate each individual word in the phrase entered (also called parsing the string). There are (at least) several problems that I see with your logic. First, the string input will never have a space in it. The >> will stop input into variable at first whitespace char and terminate a char array with a null terminating char for you. If you want whitespace chars in the string you need to use one of the versions of getline(), getline(streamName, stringName) version if you use STL strings. Second, you don't null terminate the string (that is, word) you create with the char by char review so trying to use the char array as a string won't work. Third, you don't reset y to 0 for each new word you isolate. Actually, you should probably use a different variable to keep track of where you are in each new word other than y.

    EDIT: hk_mp5kpdw's response to my problems two and three is better.
    Last edited by elad; 05-25-2005 at 12:22 PM.
    You're only born perfect.

  11. #11
    They Call me Mister Sako
    Join Date
    Jul 2004
    Posts
    169
    is there a way to have a single input into a variable that has spaces?

    edit: nevermind the person above this post answered my question
    AIM: MisterSako | MSN: sakotheinsane@hotmail.com | E-mail: klinerr1@nc.rr.com
    The goal of computer science is to be lazy

  12. #12
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    I would suggest:

    1. Use the getline function to get a whole string up to the first newline character into your target string.
    2. Initialize an istringstream object with the target string (include the <sstream> header for this).
    3. Loop through extracting data from the istringstream object while copying the individual words into your array up until the maximum number of words for your array. Better yet, push the individual words into an STL container of some sort, i.e. vector<string> perhaps.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  13. #13
    Registered User
    Join Date
    May 2005
    Location
    Sidman, PA
    Posts
    2
    Another problem I see is, what if more than 50 words are entered? It'd be so easy to do a buffer overflow in your program. You might want to use vectors or deques.

    I'm unsure what those scramble functions are for? Not related, but they aren't doing anything.

  14. #14
    They Call me Mister Sako
    Join Date
    Jul 2004
    Posts
    169
    does string variable types not hold spaces or does the >> what casue it not to be able to have spaces?
    AIM: MisterSako | MSN: sakotheinsane@hotmail.com | E-mail: klinerr1@nc.rr.com
    The goal of computer science is to be lazy

  15. #15
    Registered User
    Join Date
    May 2005
    Location
    Sidman, PA
    Posts
    2
    No, when you use cin, it stops at the first whitespace character. If you use:
    Code:
    getline(cin,input,'\n');
    It'll take a whole line of input.

    Edit: correction, I meant when you use >>

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. from 2D array to 1D array
    By cfdprogrammer in forum C Programming
    Replies: 17
    Last Post: 03-24-2009, 10:33 AM
  3. Replies: 7
    Last Post: 11-25-2008, 12:50 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21