Inputting to an array.

This is a discussion on Inputting to an array. within the C++ Programming forums, part of the General Programming Boards category; Hi, the following program is designed to take a string of input from the user and then put it into ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    45

    Inputting to an array.

    Hi, the following program is designed to take a string of input from the user and then put it into an array and manipulate it. For example, if they were to type 'hi', it would be translated to an array of {'h','i' }. Currently, I cannot get my program to work like this:

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        int test;
        int x;
        int position=0;
        char sample[8];
        cout << "-> ";
        cin >> sample[];
        cout << "The First character you entered was " << sample[0] << "\n";
        cout << "The second character you entered was " << sample[1] << "\n";
        if(sample[2]=='h') 
        {
                          cout << "You did type the letter h";
        }
        return 0;
    }
    .

    Thanks in advance for your help,
    mintsmike

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,256
    It should be:
    Code:
    cin >> sample;
    or more accurately:
    Code:
    cin >> std::setw(8) >> sample;
    (Oh, and you should #include <iomanip> for std::setw().)
    Last edited by laserlight; 03-27-2009 at 10:15 AM.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
        cin >> sample[];
    You are trying to read a string. Remove the [].

    Once you do that, it should compile correctly (I think). It's not quite clear what you are trying to achieve, so I'm not sure if it does what you want.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    45
    Thanks folks, all of your replies work.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 08:25 PM
  2. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 10:54 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 08:48 PM
  5. Array Program
    By emmx in forum C Programming
    Replies: 3
    Last Post: 08-31-2003, 01:44 AM

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