1

Today I exported my program code from Code::Blocks to Visual Studio (I recently switched to using VS), yet when I built it and tested it I received some unexpected results. This is just the faulty fragment of the code:

#include "stdafx.h"
#include "iostream"
using namespace std;

int main()
{
char service[50], key1[] = "1", s[1000];
cout << "Please select one of the following services:\n1 - Text.\n2 - Numbers.\n\n";
cin >> service;

if (strcmp(service, key1) == 0)
{
    cout << "\nPlease insert your word/phrase. Press 0 to return.\n\n";
    cin.clear();
    cin.sync();
    cin.getline(s, 100);
    cout << endl;
}
return 0;
}

... with the result: result of running the code

As you can see, I can input the "service" variable (1) just fine, yet the console won't let me input "s"/the phrase, simply skipping and going for the cout << endl followed by the end of the runtime.

*The reason I initialized the variable "service" as char and not int is because the program returns the user to the initial menu in the case where they input a non-digit value. However, I bump into the exact same problem regardless if I use the first input variable as an int or not.

Yet, if I try to input my word using cin and not cin.getline, it will actually work. But this is only a small comfort, as I'd often need to type entire phrases and not just mere words. Even then, I'd encounter the same problem when the code later on asks me to input a new value for the "service".

I am using the latest version of Visual Studio (Community 2017) and created the project as a Win32 Console Application.

If anyone knows a workaround for this I would very much appreciate any help, thank you.

Rakete1111
  • 42,521
  • 11
  • 108
  • 141
Eludium
  • 51
  • 1
  • 1
  • 6

0 Answers0