Default string with cin.getline()?

This is a discussion on Default string with cin.getline()? within the C++ Programming forums, part of the General Programming Boards category; Quick Question: Code: char name[256] cin.getline(name,256,'\n'); ... How could I make something like "Krak" be the default name? You know, ...

  1. #1
    People Love Me
    Join Date
    Jan 2003
    Posts
    412

    Question Default string with cin.getline()?

    Quick Question:

    Code:
    char name[256]
    cin.getline(name,256,'\n');
    ...
    How could I make something like "Krak" be the default name? You know, the user has the option of keeping the default name, or pressing backspace and changing it?

  2. #2
    Registered User
    Join Date
    Sep 2002
    Posts
    1,640
    I'm not really sure CIN even has this feature, But as i said earlier,
    You can always make your own input that supports whatever you
    want.

  3. #3
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Krak, your problem seemed interesting... so I decided to try and find a solution. Although non-standard, this works:
    Code:
    #include <ostream>
    #include <vector>
    #include <string>
    #include <conio.h> // :(
    
    inline void backspace(std::ostream &stream, char replace = ' ')
    {
    	stream << '\b' << replace << '\b';
    }
    
    std::string GetInputDefault(std::ostream &out, const std::string &defaultin)
    {
    	size_t defaultlen = defaultin.size();
    
    	std::vector<char> inputvec;
    	for (int i = 0; i < defaultlen; i++)
    		inputvec.push_back(defaultin[i]);
    
    	out << defaultin;
    
    	bool done = false;
    	while (!done)
    	{
    		while (!kbhit()) {}; // While a key hasn't been hit
    
    		int in = getch(); // Get keycode
    		switch (in)
    		{
    		case 13: // Enter
    			done = true;
    			break;
    		case 8: // Backspace
    			if (inputvec.size() != 0) // We can only remove defaultlen elements
    			{
    				inputvec.pop_back(); // Remove last element
    				backspace(std::cout); // Print a backspace
    			}
    			break;
    		default:
    			inputvec.push_back(in); // Add element
    			std::cout << static_cast<char>(in); // Nothing special, print it
    		}
    	}
    
    	std::string returnstring;
    	for (i = 0; i < inputvec.size(); i++)
    		returnstring += inputvec[i];
    
    	return returnstring;
    }
    You don't need to know how either of those two functions work if you don't want to... just stick them in a header file. Here's an example of how it's used:
    Code:
    #include <iostream>
    #include <string>
    
    int main(int argc, char **argv)
    {
    	std::cout << "Please Enter your name: ";
    	std::string name = GetInputDefault(std::cout, "Krak");
    	
    	std::cout << '\n' << name << '\n';
    	return 0;
    }
    Have fun!
    If you have any problems, i'll be glad to help you further.
    Last edited by Eibro; 01-31-2003 at 08:02 PM.

  4. #4
    Registered User
    Join Date
    Dec 2001
    Posts
    479
    eibro you forgot " i " in include <ostream>
    as <iostream>

  5. #5
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Originally posted by pode
    eibro you forgot " i " in include <ostream>
    as <iostream>
    No, I did that on purpose... the functions in the header only depend on <ostream>, no sense in including <iostream>

  6. #6
    Registered User
    Join Date
    Dec 2001
    Posts
    479
    well then u did wrong cause i get errors with ostream
    included
    but it works fine with iostream

    even tested your program?

  7. #7
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Originally posted by pode
    well then u did wrong cause i get errors with ostream
    included
    but it works fine with iostream

    even tested your program?
    Yes, the program works fine.

    The #includes in the header file are fine.
    You have to #include <iostream> and <string> in your main cpp file, I neglected to do that in the example above. I figured it'd be pretty trivial for someone to add them themselves.

  8. #8
    Registered User
    Join Date
    Dec 2001
    Posts
    479
    ok, whatever!

  9. #9
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Eibro, he's correct, your code is lacking some headers.

    You're using cout in your function, it's declared in <iostream>, not <ostream>

    size_t is declared in <cstddef> and is part of the std namespace.

    Addtionally, I had to change the second for-loop to make your function compile. Remember that variables declared inside the for-statement resides within the scope of the loop.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  10. #10
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    OK, now I got the function to work in CodeWarrior. It works nice, good job. Too bad that it requires the non-standard conio.h, though.
    I had to flush cout after every printed character.

    Here's how it turned out:
    Code:
    #include <iostream>
    #include <vector>
    #include <string>
    #include <conio.h> // :(
    #include <cstddef>
    
    
    std::string GetInputDefault(const std::string &defaultin)
    {
    	std::size_t defaultlen = defaultin.size();
    
    	std::vector<char> inputvec;
    	for (int i = 0; i < defaultlen; i++)
    		inputvec.push_back(defaultin[i]);
    
    	std::cout << defaultin << std::flush;
    	
    	bool done = false;
    	while (!done)
    	{
    		while (!kbhit()) {}; // While a key hasn't been hit
    
    		int in = getch(); // Get keycode
    		switch (in)
    		{
    		case 13: // Enter
    			done = true;
    			break;
    		case 8: // Backspace
    			if (inputvec.size() != 0) // We can only remove defaultlen elements
    			{
    				inputvec.pop_back();      // Remove last element
    				std::cout << "\b \b" << std::flush; // Print a backspace
    			}
    			break;
    		default:
    			inputvec.push_back(in); // Add element
    			std::cout << static_cast<char>(in) << std::flush; // Nothing special, print it
    		}
    	}
    
    	std::string returnstring;
    	for (int i = 0; i < inputvec.size(); i++)
    		returnstring += inputvec[i];
    
    	return returnstring;
    }
    One more idea: if <windows.h> is available, the kbhit()-loop can be replaced with
    Code:
    while (!kbhit()) {Sleep(50);}; // While a key hasn't been hit
    This avoids 100% processor usage.
    Last edited by Sang-drax; 02-01-2003 at 05:32 AM.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  11. #11
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    Wouldn't it be easier and more natural to just throw the name in a class and have it default to something?
    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Name {
      string myname;
    public:
      Name(string init = "Krak");
      string access(string set = "");
    };
    
    Name::Name(string init): myname(init)
    {}
    
    string Name::access(string set)
    {
      // Magic access :-)
      return (set == "") ? myname : myname = set;
    }
    
    int main()
    {
      Name me;
      char option;
    
      cout<<"The default is "<< me.access() <<", would you like to change? (y/n): ";
      if (cin.get(option) && toupper(option) == 'Y')
      {
        string new_name;
    
        cin.ignore();
        cout<<"Enter your name: ";
        getline(cin, new_name);
    
        cout<<"Your name is now "<< me.access(new_name) <<endl;
      }
    }
    *Cela*

  12. #12
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Originally posted by Sang-drax
    Eibro, he's correct, your code is lacking some headers.

    You're using cout in your function, it's declared in <iostream>, not <ostream>

    size_t is declared in <cstddef> and is part of the std namespace.

    Addtionally, I had to change the second for-loop to make your function compile. Remember that variables declared inside the for-statement resides within the scope of the loop.
    Ahh shoot, I see where I used cout in GetInputDefault... that should be changed to out (the ostream passed to the function) sorry about that.

    The for loop problem is a bug with MSVC++ 6, which is what I was compiling with. Although non-standard, it was the only way for me to get it to work. Taking everyones suggestions into account, this is what I came up with. (attached)
    I only have a single (bad) compiler installed right now... so I'm unsure of whether that code will work on other (standard) compilers/platforms.
    Attached Files Attached Files
    Last edited by Eibro; 02-01-2003 at 10:56 AM.

  13. #13
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Hehe, you're still using cout in your header

    Anyway, I don't really see the reason for the ostream& parameter. The only reasonable argument is cout, other arguments won't make sense.

    Apart from that, it's a nice function.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  14. #14
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Originally posted by Cela
    Wouldn't it be easier and more natural to just throw the name in a class and have it default to something?
    No. This function is more convenient and better for the user than answering y/n-questions in my opininon.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  15. #15
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Originally posted by Sang-drax
    Hehe, you're still using cout in your header

    Anyway, I don't really see the reason for the ostream& parameter. The only reasonable argument is cout, other arguments won't make sense.

    Apart from that, it's a nice function.
    Grrrrr I can't believe I left it in there Now i'll have to go back and edit it...
    Does the updated code compile on codewarrior? (minus my stupid error) The scope fix should allow it to compile on VC6 and other compilers.

    Hmm, this wouldn't work for ofstream arguments would it? If not, cerr would be one other valid argument to the function.

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

Similar Threads

  1. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  2. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 09:33 PM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 02:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 01:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM

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