using cin and wcin in the same program

Mar 9, 2009 at 4:25pm
Hello,
I try to learn C++ and have a question regarding cin, wcin and unicode.

I wanted to write a small program which opens a file and if the file doesn't exist it should ask the user if he wants to try another filename. Can anyone tell me if using wcin, wifstream,... instead of cin, ifstream is enough to make the program unicode aware (please look at my example code)? The second question I have is about using cin and wcin. The code below doesn't work. After I check if the file could be opened the wcin funtion doesn't wait for my keyboard input, instead it will directly go to the else case.

Non working code (will compile, but doesn't work as expected):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <fstream>

using namespace std;

int main(const int argc, const char *argv[])
{
  setlocale(LC_ALL, "");

  wchar_t yesNo;
  wifstream file;

  do
  {
    wcout << L"Please enter filename: " << endl;
    string filename;
    cin >> filename;
    file.open(filename.c_str());
    if (!file)
    {
      wcout << L"Do you want to try to open another file?" << endl
            << L"(y)es/(n)o: " << endl;
      wcin >> yesNo;
      if ( yesNo == 'y' )
        {
        }
      else
        {
          return -1;
        }
    }
    else
    {
      break;
    }
  } while (1);

  file.close();

  return 0;
}  


This code works. It's the same program as above, except for the difference that it doesn't use any "w"-functions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <fstream>

using namespace std;

int main(const int argc, const char *argv[])
{

  char yesNo;
  ifstream file;

  do
  {
    cout << "Please enter filename: " << endl;
    string filename;
    cin >> filename;
    file.open(filename.c_str());
    if (!file)
    {
      cout << "Do you want to try to open another file?" << endl
            << "(y)es/(n)o: " << endl;
      cin >> yesNo;
      if ( yesNo == 'y' )
        {
        }
      else
        {
          return -1;
        }
    }
    else
    {
      break;
    }
  } while (1);

  file.close();

  return 0;
}  


The following also code works. It will wait for the user to enter a letter:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>

using namespace std;

int main(const int argc, const char *argv[])
{
  setlocale(LC_ALL, "");

  wchar_t yesNo;

  wcout << L"Do you want to try to open another file?" << endl
            << L"(y)es/(n)o: " << endl;
  wcin >> yesNo;
  if ( yesNo == 'y' )
    {
      wcout << L"You chose yes." << endl;
    }
  else
    {
      wcout << L"You chose no." << endl;
    }

  return 0;
}  


Last edited on Mar 9, 2009 at 4:28pm
Topic archived. No new replies allowed.