I'm using the scite text editor (I cannot make use of any IDE or compiler since I'm required to also utilize Makefiles which is only possible if I use some sort of text editor) for all of my coding in c++. However, I'm consistently facing the same challenge; the text editor (I've attempted this on multiple ones including codepad and sublime text) isn't reading any input from the keyboard. Here is the source code:
#include <iostream>
#include <iomanip>
using namespace std;
const int SIZE_OF_ARRAY = 5;
int main(){
int x, y;
int counter = 0;
int elements[SIZE_OF_ARRAY];
cout << "Please enter a number ";
cin >> x;
cin.ignore();
cout << "Please enter a choice ";
cin >> y;
if(y == 1){
for(int i = 0; i < SIZE_OF_ARRAY; i++)
elements[i] = -1*SIZE_OF_ARRAY + x;
for(int j = 0; j < SIZE_OF_ARRAY; j++)
cout << elements[j] << " ";
}
else if(y == 2){
for(int i = 0; i < SIZE_OF_ARRAY; i++){
if(i == 0)
elements[i] = -1*x;
else{
elements[i] = elements[i-1] + 1;
}
}
for(int j = 0; j < SIZE_OF_ARRAY; j++)
cout << elements[j] << " ";
}
else if(y == 3){
for(int i = 0; i < SIZE_OF_ARRAY; i++){
counter++;
elements[i] = 7*x*counter;
}
for(int j = 0; j < SIZE_OF_ARRAY; j++)
cout << elements[j] << " ";
}
}
The program is supposed to take as an input any number from the user and, depending on a numeric choice (between one and three) entered by the user, manipulate the value first entered somehow.
Choice one (User picks first choice)
The program negates the size of the array and adds the number which the user first entered and fills the array with the resulting value.
Choice Two (User picks second choice)
The program negates the number entered by the user, places this in the first array location then each successive element is added one unit more than the previous one.
Choice Three (User picks third choice)
Fills the array with the first five multiples of seven. Then shifts each number by a factor equivalent to the number the user had first entered.
I've ran it on an IDE (Codeblocks) and it works perfectly well. However, on any text editor, the 'cout' statements are printed with the variables x and y taken to each be equal to zero rather than being set to the value entered from the keyboard. It doesn't even allow any keyboard input. Any answer regarding how I can fix this would be immensely appreciated.
Hoosain, continuing from the comments above, when you use an IDE, you must configure the path to your compiler as well as all compiler options you wish to use, and the location for the resulting executable and object files, etc. When you used CodeBlocks on windows, you essentially got lucky that CodeBlocks will automatically detect whether MinGW is installed and set its compiler configuration to allow you to build and run your code without you having to configure the compiler details. Geany is another editor that does a good job auto-detecting and using MinGW.
For the remaining IDE's it is up to you to configure them to find and use the compiler you have installed (MinGW), as well as configuring all desired compiler options (at minimum enable compiler warning with -Wall -Wextra).
That is where new programmers who have only used an IDE configured for them run into problems... Before you can tell an IDE where your compiler is located and which compiler options you want to use, you have to know where you compiler is located and understand what minimum set of compiler options you should use.
The way you learn to use a compiler is with the good old command line. (yep, that's cmd.exe on windows, often labeled as the "DOS Prompt" in earlier versions) An IDE is just a front-end to your compiler that executes the same commands you can simply enter on the command line to compile your program.
Learning how to use your compiler will save you an incredible amount of time when learning to code. You can simply open a command prompt and compile any file you wish, without setting up a project, etc.. When learning to code, trying to shoehorn small examples into an IDE is much more time consuming and often more trouble than it is worth. Rather than worry how to use an IDE, focus on "how to use your compiler" first.
Since you have MinGW installed on windows, all you have to do to be able to compile from the command prompt is add the path to the MinGW bin directory to your User Environment. You do that by adding the PATH as an Environment Variable here:
Start Menu-> (rt-click on Computer)-> Properties->
Advanced System Settings-> (Advanced tab)-> Environment Variables
In the Top window (your user variables), click to add (or edit) the PATH "Variable name". Generally, if you installed MinGW in the default location, you simply add the path as the "Variable value":
c:\MinGW\bin;c:\MinGW\mingw32\bin
(verify the path on your computer)
(note: windows separates path components by the semi-colon, so if there is already a PATH variable set, just add a semi-colon between what is there and what you add. Also if you already have a command prompt open, you must close it and open it again for the new path to take effect) Just open Start Menu-> Accessories-> Command Prompt (you can rt-click on the icon (top-left) and choose Properties to set the font (recommend Lucida Console 12) and height/width)
Now you have configured your command prompt to allow you to compile any file at any location within your filesystem. For example, I tested with the code you posted (I modified it to add prompts for the information). Compiling it is a piece of cake. I keep my executables in a bin directory to keep sources and binaries separate.
I named your file array_get.cpp.
Compile
Then just enter the normal g++ compiler command, and at minimum use -Wall -Wextra options to enable compiler warnings (you can add -pedantic and whatever additional warnings you want, I would recommend at least adding -Wshadow so your compiler will warn on any variables you declare in multiple scopes that could conflict). The -o option allows you to specify the location of the executable (I just use a separate bin directory as explained above). So to compile and link your code into bin\array_get.exe all I have to enter is:
C:\Users\david\Documents>g++ -Wall -Wextra -o bin\array_get array_get.cpp
(do not accept code until it compiles without warning -- read any warning (it gives line of problem), understand what it is telling you, and go fix it)
Example Use/Output
C:\Users\david\Documents>bin\array_get.exe
Please enter a number: 21
Please enter a choice (1-3): 3
147 294 441 588 735
That's it. Since MinGW uses gcc, the compiler commands you use on windows are the exact same you would use in Linux, so learning to compile from the command line pays double-benefit.
Now you have the luxury of using any text-editor to edit your code while you have the command prompt simply and easily re-compile as you wish until your code is correct. No project dialogs, no mess of a different folder for every file, just the freedom to compile any file you wish -- right from the command line. (I actually separate my sources in directory by type, e.g. c, cpp), you find what works best for your. I also use a simple bat file that takes the exename and source.cpp names as arguments and then compiles with the options I set -- it just cuts down on typing :)
Further, since you now where your compiler is located, and which options to use, you can open the Settings window on any IDE and set the appropriate compiler command and compiler options to allow the IDE compile your code for you. Give it a try, and let me know if you have further questions.
Related
I have a C++ file code.cpp, and an input file input.txt. After compiling, I want to run the file from vim like code.exe < input.txt. Doing !$code_dir < $input_dir does not work. What's the fix?
Vim perfectly supports
:!path/to/executable < other/path/to/file
It doesn't work with :term path/to/exec < path/to/file though -- unlike neovim that has no troubles here.
Given the simple
#include <iostream>
int main()
{
std::string line;
while (std::getline(std::cin, line)) {
std::cout << line << "\n";
}
}
compiled with :make %< (I'm using g++-cygwin and not g++-mingw), :!./%< < % works perfectly.
In case what I've just described doesn't work, as I see a windows tag, maybe your &shell* options are incorrectly set? With Windows, I had to change the default as I use the native gvim with cygwin. In a pure windows environment, I make sure my settings are (don't ask me why, this is the result of 15-20 year old experimentations and I definitively don't remember all the tests I made)
let &shell=$COMSPEC
set shellslash
set shellcmdflag=/c
set shellquote=
set shellxquote=
set shellredir=>
set shellpipe=>
I am using Visual Studio and I want to run a simple program that uses cin to read input parameters
#include <iostream>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
cout << n << k;
return 0;
}
Now I want to run the program passing this two parameters.
I usually run by pressing Ctrl+Alt+N or just right clicking and selecting Run but I don't see how can I input my parameters.
When I run, VisualStudio basically does:
cd "/home/user/codeforce/" && g++ 977A.cpp -o 977A && "/home/user/codeforce/"977A
Is there a way to input parameters so they are read by cin?
Start from the top: Press CTRL + f5 to run the program. A prompt will ask you if you want to Save\Build the project. Click 'yes' to both. A console window will appear, and based on your code, it will just be blank with a flashing cursor waiting for you to enter your values for n and k. Keep in mind that your code will take values for both n and k at the same time if you have any spaces, so if you input
10 45
the output will be
1045
The default keyboard shortcut Ctrl + Alt + N in Visual Studio corresponds to TSqlEditorCloneQuery.
I suggest you could follow the following steps to build and run your code in Visual Studio:
1,To build your project, choose Build Solution from the Build menu. The Output window shows the results of the build process.
2,To run the code, on the menu bar, choose Debug, Start without debugging.
A console window opens and then runs your app. When you start a console app in Visual Studio, it runs your code, And then you could enter values for n and k.
Personally I do not use VisualStudio because it is very complicated compared to other editors, such as Atom or even command line editors such as vim. I did a quick research and found this.
Properties -> Debugging -> Command Arguments
I want to debug this code segment:
#include <iostream>
#include <queue>
#include <random>
#include <time.h>
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
queue<int> q;
srand(time(NULL));
for(int i = 0; i < 10; i++)
{
q.push(rand() % 100);
}
int a = q.front();
q.pop();
int b = q.front();
q.pop();
cout << "a: " << a << ", b: " << b << endl;
return 0;
}
I tried to debug it on 2 IDEs - CLion (my personal favorite) and VS2015. However, both of those did not show the queue items (as they would if I'd use an array, for instance):
CLion
VS2015
As I continued investigating, I noticed that if I remove the upper breakpoint in CLion, it does show the queue elements:
CLion - good version
Any ideas about why does it happen, and if there's a way to see the queue elements in the "bad" cases?
Removing the upper break point and switching between 32 and 64 bit compilations won't affect this. The 32/64 bits have to do with the generated assembly code. Once the code compiles correctly, the 32 and 64 bit assembly codes won't be the same but the program itself will still retain equivalent functionality. That is, 64 bit programs can't "do more" than 32 big programs. This is an ultra watered-down definition of Turing-completeness, but the upshot here is that it doesn't matter for the purposes of what you're trying to do right now whether you set your build target to 32 or 64 bits.
The IDE that you use will have a minimal effect here though, because they use different Debuggers. Since both debuggers did the same thing in your case, I'd say we can safely chalk it up to user error (see below), but like I said in my afterword, if you will, keep working with the debugger. It's an absolutely essential skill to master. Props to you for getting started early.
As for your debug problem, here is my debug of your program. Notice the breakpoints I used. Like Jesus Christ said before me, the debug worked correctly for both of us. The usual suspect in these cases is trying to debug the release build. When you compile a debug build, the compiler does not perform as many optimizations to allow you to trace your code through the variables and see exactly what's going on. Once your code functions correctly, you can switch to the release version and your compiler will optimize away a lot of the variables for maximum performance.
If you did debug under the Debug build as you said, then I'd say just chalk it up to debugger error. If you're a C++ newbie, there's a chance you just might not be experienced enough to navigate the intricacies of the debugger. No disrespect intended, but debugging is just as much an art as it is a science, and a new developer would not be faulted for not knowing how exactly to maneuver the tool.
I found a solution for the CLion problem - simply press on the variable in the variables tab, then press on Duplicate Watch (marked in red circle bellow, hotkey: ctrl+D) and you're done:
Did you compile with debug selected in the project?
I can clearly see queue values.
Make sure that
1) you are debugging Debug build (that is debug information is present and no optimization is done)
Project Properties -> C/C++ -> General -> Debug information format is set to "Program Database"
Project Properties -> Linker -> Generate Debug info is set to "/DEBUG")
2) raw structure mode is disabled
Tools -> Options -> Debugging -> Show raw structure of objects is not checked
Unfortunately a program I wrote in C++ has a bug (or bugs), yet I can't deduce what it is since only a single output line doesn't match the expected output (the input file has 3K lines of input). I know which input line is the problematic, yet it's over 2K lines into the input file so debugging it manually isn't very efficient.
Is there any way to let the debugger run "alone" with the first 2K lines and stop exactly before trying to execute the problematic input line? I use Windows and eclipse but don't mind switching the IDE or switch to Linux if necessary.
Thanks in advance!
Don't reinvent the wheel!
Eclipse has powerfull feature Enable condition for breakpoint.
Set breakpoint in your code
Right-click on breakpoint - "Breakpoint properties"
Check "Conditional"
Write your condition when breakpoint should be stopped (you have access to scope and global variables)
Here is Eclipse help page. Breakpoint Enable Condition
(with screenshot)
Well, eclipse may well have advanced debugging features, and to tell the truth I do not know the first thing about eclipse, but FWIW you can easily simulate what you want.
What you have is:
for(i = 0; i < lineCount; ++i)
process one line
Add a condition to check the line number and place a breakpoint inside it!:
for(i = 0; i < lineCount; ++i)
if(i == 2000)
{
int x = i*i; //random line, just add your breakpoint here!
}
process one line
Since you know exactly what line is problematic, just a dummy if statement which would check the contents of the line, and if mathces your problem line, do nothing - and put a breakoint at this line.
Let me preface this by saying I have searched (for a few days now) for answers to these questions and can't find anything that solves the problem. In fact, I think I've only made it worse.
Also, when it comes to programming, I am a complete beginner and am teaching myself C++ (I know, I know, you're not supposed to start with C++ as your first programming language).
I know in the StackOverflow guidelines it says to describe your problem first before posting any code but part of my problem is that I don't even understand what the problem is...
For reference, I'm running Windows 7 64-bit and writing my code in Sublime Text 3 (build 3059) and, well, I'm not entirely sure what I'm compiling it with, I mean I have gcc installed(?) but I'm thinking that's part of the problem- I installed something called Cygnus as well as MinGW and Visual Studio Express 2012 but I'm not sure if these are actually compilers/I simply don't know what they do. Also, I've modified my Environment Path variable several times which was probably a bad idea.
Anyway, here is the code for the first of the two problems:
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World! ";
return 0;
}
When I "build" the code, it works fine, however when I attempt to run it, this is the error that I get:
bash.exe: warning: could not find /tmp, please create!
[sig] C:\cygnus\cygwin-b20\H-i586-cygwin32\bin\bash.exe 1020 (0) call_handler: couldn't get context of main thread, error 998
I've searched for how to add/create bash but truthfully did not understand the answers that I found.
Here is my second problem. I'm learning C++ from Stroustrup's "The C++ Programming Language, 4th Edition" which, for several chapters, asks the reader to include a header ("std_lib_facilities.h") which I have saved and placed in the folder along with my practice files. This is some code I've written myself (which is probably all wrong) but even copying code from the book and running it generates this error. (I've tried just using #include and using namespace std; however things still don't work.)
//convert from miles to kilometers. 1.609km in 1 mile
#include "std_lib_facilities.h"
int main()
{
cout >> "Please enter a length in miles: " >> endl;
float miles = 0;
cin << miles;
float kilometers = 1.609;
float result = miles / kilometers;
cout >> miles >> " miles is equal to " >> kilometers >> endl;
return 0;
}
The error it generates when I attempt to build it is extremely long so I'll post a snippet of it:
In file included from c:\users\brekki\gcc\bin\../lib/gcc/x86_64-w64- mingw32/4.7.0/../../../../include/c++/4.7.0/ext/hash_map:61:0,
from C:\Users\brekki\Desktop\CPP\MINE\std_lib_facilities.h:21,
from C:\Users\brekki\Desktop\CPP\MINE\mtokm.cpp:2:
c:\users\brekki\gcc\bin\../lib/gcc/x86_64-w64- mingw32/4.7.0/../../../../include/c++/4.7.0/backward/backward_warning.h:33:2: warning: #warning This file includes at least one deprecated or antiquated header which may be removed without further notice at a future date. Please use a non-deprecated interface with equivalent functionality instead. For a listing of replacement headers and interfaces, consult the file backward_warning.h. To disable this warning use -Wno-deprecated. [-Wcpp]
C:\Users\brekki\Desktop\CPP\MINE\mtokm.cpp: In function 'int main()':
C:\Users\brekki\Desktop\CPP\MINE\mtokm.cpp:5:10: error: no match for 'operator>>' in 'std::cout >> "Please enter a length in miles: "'
C:\Users\brekki\Desktop\CPP\MINE\mtokm.cpp:5:10: note: candidates are:
In file included from c:\users\brekki\gcc\bin\../lib/gcc/x86_64-w64- mingw32/4.7.0/../../../../include/c++/4.7.0/string:55:0,
from c:\users\brekki\gcc\bin\../lib/gcc/x86_64-w64- mingw32/4.7.0/../../../../include/c++/4.7.0/bits/locale_classes.h:42,
from c:\users\brekki\gcc\bin\../lib/gcc/x86_64-w64-mingw32/4.7.0/../../../../include/c++/4.7.0/bits/ios_base.h:43,
from c:\users\brekki\gcc\bin\../lib/gcc/x86_64-w64- mingw32/4.7.0/../../../../include/c++/4.7.0/ios:43,
from c:\users\brekki\gcc\bin\../lib/gcc/x86_64-w64- mingw32/4.7.0/../../../../include/c++/4.7.0/ostream:40,
from c:\users\brekki\gcc\bin\../lib/gcc/x86_64-w64- mingw32/4.7.0/../../../../include/c++/4.7.0/iostream:40,
from C:\Users\brekki\Desktop\CPP\MINE\std_lib_facilities.h:4,
from C:\Users\brekki\Desktop\CPP\MINE\mtokm.cpp:2:
When I attempt to run the program, I get a similar error except it is preceded by the "bash.exe: warning:"
My ideas as for what the problem(s) could be are:
I've somehow screwed up my Path variables
My GCC files are outdated
Trying to use too many compilers
Bad Sublime Text 3 C++ build
Stroustrup's header causing obvious issues
Sorry for the long, possibly stupid question. Any insight at all would be extremely appreciated.
First at all, MinGW and Cygnus are just installer for the GCC compiler. As Preet Kukreti allready commented, you should try an IDE like Visual Studio Express or otherwise if you didn't want the Microsoft thing you should try CodeBlocks which is also free.
I wouldn't recommend to learn C++ on Windows without a IDE. When you want to programm C++ with a text editor and the command line, you should probably go with linux.
You may not know yet how to setup a compiler, so to make it easier for you, I recommend you to use an IDE, like Code::Blocks. It comes with a compiler (MinGW) so you don't have to install one by yourself. There are other IDE for C++, but this one is the most complete and easy-to-us I know.
Your problem with the examples from your book is that you have inverted the << and >> signs :
stream << variable goes with an output stream like cout, it won't work with an input stream whereas stream >> variable will only work with an input stream like cin.
That means your code should look like this :
//convert from miles to kilometers. 1.609km in 1 mile
#include "std_lib_facilities.h"
int main()
{
cout << "Please enter a length in miles: " << endl;
float miles = 0;
cin >> miles;
float kilometers = 1.609;
float result = miles * kilometers; //result in kilometers = length in miles * 1.609 (not /)
cout << miles << " miles is equal to " << result /*You want the result here, not the length of 1 mile in kilometers*/ << " kilometers" << endl;
return 0;
}