I'm new to C++, came from Java (started learning yesterday).
I'm trying to loop over the elements of a vector. For some reason when I do this, it endlessly outputs empty lines.
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string expression = "5+4";
std::vector<char> characters(expression.begin(), expression.end());
for (char c : characters) {
std::cout << c << std::endl;
}
}
I keep running into this problem, I have no clue why it is doing this.
I tried searching if other people had this problem, but I couldn't find any questions about it or answers... what am I doing wrong?
EDIT:
I'm using MinGW
GIF or it didn't happen
I'm not an expert in CPP, but i assume your code is inserting string to the vector and iterate through the vector, if so, heres the code :
#include <iostream>
#include <string>
#include <vector>
using namespace std; //i add this line to remove the "std" in every line
int main()
{
string expression = "5+4";
vector <char> characters(expression.begin(), expression.end());
for (int i=0; i< characters.size(); i++)
{
cout << characters[i] << endl;
}
}
An explanation that i can tell you is, you do not printing the vectors with its index so it'll have some bug also the looping i use i think more clear to see.
Related
According to Stroustrup Programming.. the below code should produce a range error. The error is in the last line i<v.size() instead of i<=v.size.
I ran the code and it outputs the contents of the vector including v[v.size] instead of throwing an exception. I am using CodeBlocks with mingw.
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
vector<int>v;
for (int x;cin>>x;) v.push_back(x);
for (int i=0;i<=v.size();i++) cout << "\nv[" << i << "]==" << v[i];
}
What error did you expect? There is no compilation error here, but there is a runtime error. When printing the read values it will always go one step too far. If you read 2 values it will print indexes 0, 1 and 2.
This can be fixed by changing i<=v.size() to i<v.size().
It is very common in indexed for-loops to always follow the following pattern; then you know you'll never be wrong:
for (int i = 0; i < count; i++) {
...
}
I've seen a couple of solutions to this question, but I'm still running into an issue. I've tried several of the solutions I've seen on this site, but I keep having the same issue. I'm not sure how to make this work, and I'm also not sure why it's not working, since I'm really new to C++.
A brief explanation of what I am attempting to do: I'm writing a simple old-school text-based story/game for a video game design club at my school, and at several points I have the user make decisions, or input things such as their name, which is then used in an output line, as it would be referenced several times. I have had no problem doing that, using something simple like this:
#include <iostream>
#include <string>
#include <limits>
#include <windows.h>
using namespace std;
int main(){
string name, place ;
cout << "???: What is your name? ";
getline (cin, name);
cout << "???: Hello, " << name << "!\n" << "\n";
}
My problem is that I'd like to have the text appear one character at a time, like dialogue, but whenever I try to use something I've seen written by others, it doesn't seem to like it very much. The only one that I tried that I can now find again is this:
#include <iostream>
#include <unistd.h> // include <windows.h> on windows
// function to output as if it was being typed
void type_text(const std::string& text)
{
// loop through each character in the text
for (std::size_t i = 0; i < text.size(); ++i)
{
// output one character
// flush to make sure the output is not delayed
std::cout << text[i] << std::flush;
// sleep 60 milliseconds
usleep(60000); // use Sleep on windows
}
}
int main()
{
type_text("Hej hej hallå!");
}
Apparently there is some sort of conflict regarding my attempt to output the name back to the user when I try to use that code with what I've written. I'm not really sure what the problem is, since I'm so new to C++, can anyone help me out?
Consider using std::this_thread::sleep_for, as it is standard C++11. Example:
#include <iostream>
#include <thread> // standard C++11
// function to output as if it was being typed
void type_text(const std::string& text)
{
// loop through each character in the text
for (std::size_t i = 0; i < text.size(); ++i)
{
// output one character
// flush to make sure the output is not delayed
std::cout << text[i] << std::flush;
// sleep 60 milliseconds
std::this_thread::sleep_for(std::chrono::milliseconds(60));
}
}
int main()
{
type_text("Hello, World!");
}
If you have access to a C++14 compiler, you can simply make use of the std::chrono user-defined literals and have a more "natural" syntax:
using namespace std::literals;
std::this_thread::sleep_for(60ms);
I can't figure out why it says this. I am new as you can probably tell... here is the code:
#include <iostream>
using namespace std
int main() {
if (cin >> "hi"
cout << "hello"
return 0;
}
"The thing you were using" (read: your compiler) wanted you to end your using namespace std statement with a semicolon, not to dump one at the start of a function definition.
Your code has a number of extreme and baffling syntax errors, to the extent that it's not even clear what you're trying to accomplish.
Below is a hint to get you started but, from now on, I strongly recommend that you read a good, peer-reviewed C++ book and learn the language before asking any further questions about nonsense code!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
getline(cin, input);
if (input == "hi") {
cout << "hello" << endl;
}
return 0;
}
I want 41 output files to use in my project to write text on them. first create a string array list to name those output files then I tried to define an array of ofstream objects and use list to name them, but I get this error that 'outfile' cannot be used as a function. Below is my code:
#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
using namespace std ;
int main ()
{
string list [41];
int i=1;
ofstream *outFile = new ofstream [41];
for (i=1;i<=41 ;i++)
{
stringstream sstm;
sstm << "subnode" << i;
list[i] = sstm.str();
}
for (i=0;i<=41;i++)
outFile[i] (list[i].c_str());
i=1;
for (i=1;i<=41;i++)
cout << list[i] << endl;
return 0;
}
See below for the following fixes:
don't use new unless you have to (you were leaking all files and not properly destructing them will lead to lost data; ofstreams might not be flushed if you don't close them properly, and the pending output buffer will be lost)
Use proper array indexing (starting from 0!)
Call .open(...) on a default-constructed ofstream to open a file
Recommendations:
I'd recommend against using namespace std; (not changed below)
I recommend reusing the stringstream. This is is good practice
Prefer to use C++-style loop index variables (for (int i = ....). This prevents surprises from i having excess scope.
In fact, get with the times and use ranged for
#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream outFile[41];
stringstream sstm;
for (int i=0;i<41 ;i++)
{
sstm.str("");
sstm << "subnode" << i;
outFile[i].open(sstm.str());
}
for (auto& o:outFile)
cout << std::boolalpha << o.good() << endl;
}
You can not call the constructor as you do. Try calling outFile[i].open(list[i].c_str()). Note the 'open'.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
char x[20];
cout << "enter something\n";
cin.getline(x,20);
ofstream o("d:/tester.txt");
//o.write( (char*)&x , sizeof(x) );
for(int i = 0 ; i<=19 ; i++ ) {
o.put(x[i]);
}
}
I am not getting that output in the file the one which i enter during program . for eg. the output is 畳慨汩朠灵慴찀쳌쳌쳌 on writing suhail gupta.
What is the problem with the code ? Even when i use o.write( (char*)&x , sizeof(x) ); (the commented statement) i get the same output.
What is the reason?
Your program involves undefined behavior. The x array is not fully initialized and you read from the uninitialized indices. Besides, you always write 20 bytes, independent of what you read from the user.
I guess you use some text editor like Notepad. The latter has bugs when trying to guess the encoding. It appears that it guesses the file is UTF16 and displays 20/2 == 10 characters instead.
To solve the problem, store to the file exactly the number of characters entered by the user. Use std::string to make it easier.
Edit: The C++ way:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string x;
cout << "enter something\n";
getline(cin, x);
ofstream o("d:/tester.txt");
o << x;
}