I have been doing some exercises to learn c++ and decided to integrate them into R since ultimately I want to write c++ backends for R functions.
I am having trouble finding a solution to retrieve user input from the R console. While there is Rcpp::Rcout for printing and returning output, there doesn't seem to be a similar funciton for std::cin....
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::String cola() {
Rcpp::Rcout << "Pick a drink:" << std::endl << "1 - Espresso" << std::endl << "2 - Americano" << std::endl << "3 - Latte" << std::endl << "4 - Cafe dopio" <<
std::endl << "5 - Tea" << std::endl;
int drink;
std::cin >> drink;
std::string out;
switch(drink) {
case 1: out = "Here is your Espresso";
case 2: out = "Here is your Americano";
case 3: out = "Here is your Latte";
case 4: out = "Here is your Cafe dopio";
case 5: out = "Here is your Tea";
case 0: out = "Error. Choice was not valid, here is your money back.";
break;
default:
if(drink > 5) {out = "Error. Choice was not valid, here is your money back.";}
}
return out;
}
Even without Rcpp in the mix, std::cin is unsuitable for interactive input.
To use the R console with Rcpp, you need to use R functions (in particular, readline) instead of C++ functionality. Luckily you can pull R objects into your C++ code:
Environment base = Environment("package:base");
Function readline = base["readline"];
Function as_numeric = base["as.numeric"];
And then you can use them:
int drink = as<int>(as_numeric(readline("> ")));
Beware that there's another error in your code: your cases are all fall-through since you are missing the break; furthermore, there’s no reason to have a case 0, and there’s no reason at all for the if in the default case.
Oh, and finally, don’t use std::endl unless you actually need to flush the output (and you only need to do this once here, at the end); use '\n' instead.
Related
Good day,
I have a loop that computes values and displays the output to the console. However, when I run the code, cout << does not display the output I expected. In fact, it doesn't display any output. The only way I know the code even works is that the values are changing.
cout << was working just fine until I used the switch statement. Every piece of text that I expected to print to the console inside the statement and the loop was just dead text. It didn't work. I also tried flushing the stream using cout.flush. That did not work either I cannot include all of my code, but here are the problem lines:
if (exampleloop == '1'){
ExampleValue = (ExampleValue - 1);
ExampleValue = (ExampleValue - ExampleValue);
cout << "ExampleText " << ExampleValue << " ExampleText";
if (ExampleValue <= 0){
cout << "ExampleText.";
}
if (ExampleValue <= 0){
cout << ExampleText";
}
example_label:
ExampleValue = (ExampleValue1 - ExampleValue1);
cout << "ExampleText! " << ExampleValue! << " ExampleText!";
goto Example_label;
}
And the only way I know that the code is being computed
cout << "EXAMPLE TEXT ExampleValue1 at "<< ExampleValue <<" . ExampleText";
In this case, "Example Text" would never appear on the console. However, the "Example Values" would be computed and the changes would reflect on the code above.
My IDE is repl.it
Is this my fault, or my IDE's? And what is going on?
(Yes, I #include iostream and I'm using namespace std)
I am fairly new to C++ and have been tinkering with some simple programs to teach myself the basics. I remember a little while ago installing MinGW on my desktop (I think for the C compiler). I decided to go for Cygwin for C++ and it seems to have been working a treat, up until I noticed that it seems to behave differently from the MinGW compiler for this program. I'm probably breaking some coding golden rule, but the reason for this is that Windows CMD uses the MinGW compiler, or I can open the Cygwin shell and use that instead. Variety!
For the program below, I am making notes on the ternary operator and switch statement. I initialize 'a' and 'b', ask for user input, and then use a function to check which is larger.
I then ask for user input again, to over-write the values in 'a' and 'b' to something else. When compiling from Windows CMD, this works fine and I can overwrite with new input, and the #define MAXIMUM and MINIMUM functions work fine on the new values. When I compile on Cygwin, however, after the first 'pause', the program launches past the two std::cin's and just runs MAXIMUM and MINIMUM on the old values of 'a' and 'b'.
Obviously I have tried just creating two new int variables, 'c' and 'd', and then there is no issue. The values are not immutable in any sense that I am aware of (although I don't know much, so I could be wrong).
I wasn't sure if this was something to do with the auto keyword, so I specified the type as int manually.
I also checked the version of both compilers with 'g++ -v' in Cygwin and at the CMD.
#include <iostream>
#include <cstdlib>
#define MAXIMUM(a,b) ((a > b) ? a : b)
#define MINIMUM(a,b) ((a < b) ? a : b)
int ternary_op(int a, int b)
{
char x = 'a';
char y = 'b';
auto result_var = 0;
result_var = a > b ? x : y; //Shorthand if statement with syntax (test_condition) ? (if_true) : (if_false)
return result_var;
}
int main()
{
auto a = 0;
auto b = 0;
auto larger = 0;
auto smaller = 0;
std::cout << "Enter an integer: " << "\n";
std::cin >> a;
std::cout << "Enter another integer: " << "\n";
std::cin >> b;
char greater_var = ternary_op(a,b); //Therefore if condition a > b is satisfied, greater_var is assigned x ('a')
std::cout << greater_var << std::endl;
switch(greater_var){
case 'a':
std::cout << "First integer " << a << " is larger than second, " << b << std::endl;
break;
case 'b':
std::cout << "Second integer " << b << " is larger than first integer, " << a << std::endl;
break;
}
std::cout << system("cmd /c pause") << std::endl;
std::cout << "We can also use defined functions to check equivalency and assign variables based upon the result." << "\n";
std::cout << "Enter an integer: " << std::endl;
std::cin >> a;
std::cout << "Enter another integer: " << std::endl;
std::cin >> b;
larger = MAXIMUM(a,b);
smaller = MINIMUM(a,b);
std::cout << "Larger and smaller numbers determined by defined function: " << larger << ", " << smaller << std::endl;
std::cout << system("cmd /c pause") << std::endl;
return 0;
}
Obviously if I make two new variables, 'c' and 'd', there is no issue. Changing the type to int myself did not change the way the program behaved using Cygwin. Unusually the MinGW version was 8.1.0, while Cygwin was 7.4.0. I'm not sure if this means that it is simply an older version of the same compiler.
Again, I'm very new to this so I'm just quite confused as to why they would behave so differently. I was also under the impression that different compilers were completely different beasts that simply read from the same standard hymn sheet, so to speak.
Just curious as to what is going on here!
Cheers!
In my c++ class, we have been tasked to keep building different aspects into this code. I am currently getting 2 errors and am stuck where I don't know what I am doing wrong. The program takes a private car or string for a name and a private integer to be input into the game checking for divisibility by 3, 5, and both 3 & 5. I am to use a get function and a put function within the class taking the input values and outputting them. I have essentially figured out the program but it will not compile and I am really unsure why. Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
using std::istream;
// declare the max size the username input can be
const int MAX = 14;
enum FIZZBUZZ { ABORT = 0, FIZZBUZZ, FIZZ, BUZZ };
class CFizzbuzz // Class definition at global scope
{
// make sure our constructor, destructor, plus member functions are
// all public and available from outside of the class.
public:
CFizzbuzz() {} // Default constructor definition
~CFizzbuzz() {} // Default destructor definition
// function members that are public
// get the user's name and their value from the console and
// store those results into the member variables.
void getFizzbuzz()
{
cout << "Please enter your name: " << endl;
cin >> m_myName;
cout << "Please enter your number for the FizzBuzz game: " << endl;
cin >> m_myNum;
}
// return the user's number type entered
int putFizzBuzz()
{
return m_myNum;
}
char* getName()
{
return m_myName;
}
// logic to check to see if the user's number is 0, fizz, buzz, or fizzbuz
int getRecord(int num)
{
if (num == 0)
{
return ABORT;
}
else if (num % 5 == 0 && num % 3 == 0) // fizzbuzz number
{
return FIZZBUZZ;
}
else if (num % 5 == 0) // buzz number
{
return BUZZ;
}
else if (num % 3 == 0) // fizz number
{
return FIZZ;
}
else
return num;
}
// private data members only available inside the class
private:
int m_myNum;
char m_myName[MAX];
};
int main()
{
CFizzbuzz myClass;
cout << "Welcome to my Fizzbuzz game, you are to guess the location of a "
<< "number which if is divisible by 5 and 3 you will win with "
<< "the output of Fizzbuzz. " << endl;
cout << "Please enter an integer value between 0 and 3 "
<< "representing the row location of the number for the game, "
<< "then press the Enter key: " << endl;
for (;;)
{
myClass.getFizzbuzz();
int num = myClass.putFizzBuzz();
switch (myClass.getRecord(num))
{
case ABORT:
cout << myClass.getName() << "\nThank you for playing\n";
system("PAUSE");
return 0; // exit program
case FIZZ:
cout << "Sorry, " << myClass.getName() << ", number is a Fizz, please try again.\n";
break;
case BUZZ:
cout << "Sorry, " << myClass.getName() << ", number is a Buzz, please try again.\n";
break;
case FIZZBUZZ:
cout << "You win you got FizzBuzz!!!" << endl;
break;
default:
cout << "Sorry, " << myClass.getName() << ", number is a not a Fizz, Buzz, or Fizzbuzz\nPlease try again.\n";
break;
}
}
}
These are errors I'm getting:
LNK2019, LNK1120
Based on the errors you mentioned in comments (Unresolved external symbol _WinMain#16) I'd say that you created a Win32 project (a GUI project) in Visual Studio but your code is meant to be a console application.
You need to change the type of your project from Win32 application to Console application by either re-recreating it or changing the Subsystem from Windows to Console in project settings. See the following link for more information on the latter:
https://msdn.microsoft.com/en-us/library/fcc1zstk.aspx
I would be suspicious of the else return num. What happens when you enter 1 or 2? Clearly the modulus doesn't provide a fizz or buzz but based on your enum values the function getRecord() returns that it does. I would have a NONE enum value set to -1 to indicate that it is neither a fizz or buzz.
The thing to remember about an enum value is that it resolves to an actual number when compiled. So when you input 1, and the modulus doesn't prove a fizz, buzz, or a fizzbuzz AND you return 1, the switch case statement will resolve to fizzbuzz even though this is not the case (pun intended).
As far as you commenting that it's not working as expected, please input more details.
Hi I am working on some C++ code in Xcode and I get this error Control may reach end of non-void function. I am also using the Unreal engine standard for code so that is where the FText and int32 comes from. Here is my code:
do {
// get a guess from the player
int32 CurrentTry = BCGame.GetCurrentTry();
std::cout << std::endl;
std::cout << "Try " << CurrentTry << ". Enter your guess: ";
FText Guess = "";
std::getline(std::cin,Guess);
Status = BCGame.CheckGuessValidity(Guess);
switch (Status)
{
case EGuessStatus::Wrong_Length:
std::cout << "Please enter a " << BCGame.GetHiddenWordLength() << " letter word.\n";
break;
case EGuessStatus::Not_Isogram:
std::cout << "Please enter a word without repeating letters.\n";
break;
case EGuessStatus::Not_Lowercase:
std::cout << "Please enter all lowercase letters.\n";
break;
default:
return Guess;
}
} while (Status != EGuessStatus::OK);
}
Please someone help.
You are not showing your complete function, but obviously it is declared to return something; and the default path in the switch also does return Guess.
However, the other three paths in the switch do not return anything, the flow goes behind the switch and there is nothing more. So you have a function that returns nothing, but it needs to return something - just as the message said.
I'm very new to programming in C++ but I'm trying to write some code which filters a specific word from a string and then takes a specific action. For some reason the code does not see the text inside the string.
printf("%s \n", data.c_str());
cout << data;
This shows absolutely nothing - meaning I cannot use .find or write it to a file.
printf("%s \n", data);
This shows exactly what I need.
I am writing the code into data with assembly:
mov data, EDX
Why is that I can only use the the last method?
Edit:
Data is initiated as:
std::string data;
If a pointer to a string is null all subsequent calls to cout
stop working
const char* s=0;
cout << "shown on cout\n";
cout << "not shown" << s << "not shown either\n";
cout << "by bye cout, not shown\n";
The two function calls are not equivalent, as \n at printf flushes the stream. Try with:
cout << data << endl;
Be sure you used
#include <string>
in your file header. With this in place you should be able to use
std::cout << data << endl;
with no issues. If you're using a global namespace for std you may not need the std::, but I'd put it anyway to help you debug a it faster and eliminate that as a possible problem.
In Short
You will have a problem with cout, if you don't put a linebreak at it's end!
In Detail
Try adding an endl to your cout (e.g. std::cout << data << std::endl), or use following instruction to activate "immediate output" for cout (without it needing a linebreak first).
std::cout << std::unitbuf;
Complete example:
std::cout << std::unitbuf;
std::cout << data;
// ... a lot of code later ...
std::cout << "it still works";
Sidenote: this has to do with output buffering, as the name unitbuf suggests (if you want to look up what is really happening here).
This way it is also possible to rewrite the current line, which is a good example, where you would need this ;-)
Practical example
using namespace std;
cout << "I'm about to calculate some great stuff!" << endl;
cout << unitbuf;
for (int x=0; x<=100; x++)
{
cout << "\r" << x << " percent finished!";
// Calculate great stuff here
// ...
sleep(100); // or just pretend, and rest a little ;-)
}
cout << endl << "Finished calculating awesome stuff!" << endl;
Remarks:
\r (carriage return) puts the curser to the first position of the line (without linebreaking)
If you write shorter text in a previously written line, make sure you overwrite it with space chars at the end
Output somewhere in the process:
I'm about to calculate some great stuff!
45 percent finished!
.. and some time later:
I'm about to calculate some great stuff!
100 percent finished!
Finished calculating awesome stuff!