Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I need to convert a char (called reader) to a string. I tried this:
/*stringstream ss;
string convert;
ss << reader;
ss >> convert;
cout << convert;*/
And this:
string convert (1, reader);
Both do not set a value for ss or convert. I can't figure out why.
I have the name of a wavfile in a text document. I want to read from the file and open that wav. However, .get returns a char, and I need a wstring. So I'm trying to convert from char to string, then string to wstring.
#include "stdafx.h"
#include <string>
#include <iostream>
int main()
{
char c = 'a';
std::string h;
std::string str(1, c);
std::cout << str;
std::cin >> h;
return 0;
}
Why does the above code work but not the code above it?
The problem description seems quite clear, but under-specified:
” I have the name of a wavfile in a text document. I want to read from the file and open that wav. However, .get returns a char, and I need a wstring.
.get() is an ungood choice when you want to read more than one character, as you do.
If the file name is on its own line then you can use getline from the <string> header to read it, which preserves any spaces in the name. But the C++ standard library i/o does not deal sensibly with encodings, so possibly you'll have to use system specific functionality for the reading. This depends much on your text file.
Using the filename, now in a string or wstring, to open a file, also runs into encoding issues.
But as long as the filename only contains ASCII characters you can just pass it to an ifstream constructor. Visual C++, your compiler, offers an extension that takes wstring argument, so that will work. Make sure to specify binary mode for the stream, since a ".wav" file is binary.
Don't read the data as chars, use an ifstream.
Here is an example taken from a cplusplus.com tutorial (scroll down to Text files).
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I made a code but it doesn't work.Can you help? In code, I wanted to take a line and if code see //n, end line.
Here is my example.
File:
I love C++! //n
My Code:
ifstream file("file.txt");
char text[250];
while(file >> text){
cout << text << " ";
if(text == "//n"){
cout << endl;
}
}
Thanks for your help.
I am unsure as to what you are trying to do, however it seems that you want to get a line worth of text. If so, you would want to change
char text[255];
....
if(text == "//n")
to
std::string text;
...
if(text == "\n")
The array comparison will not compare strings. So use the std::string to allow you to use == operator.
As C++ special character codes use a backslash rather than two forward slashes.
However, I'd also suggest using a single char rather than an array (as indexing doesn't seem to be a concern since you only access the first character in it).
If you want to read a file a word at a time:
ifstream file("file.txt");
std::string line;
while(std::getline(file, line)) {
std::stringstream linestream(line);
std::string word;
while(linestream >> word) {
std::cout << "Word: " << word << " ";
}
std::cout << "EOL\n";
}
Basically your code has a couple of issues.
'//n' is not a special character we all assume you meant '\n'.
Most operators that read text from a file will disgard the '\n' character.
operator>> will disguard white space (including \n).
getline() reads the line but drops the \n.
Thus '\n' is never in text to be compared too.
Arrays char text[255] will convert themselves into pointers easily.
Thus the comparison you are doing compares two pointers. This will never be equal.
You need a type that does something smart with == so that you compare the text.
For this you should use std::string.
As a good style guide.
Never put using namespace std; in your code. It causes more trouble when you have anything but a simple bit of throwaway code. And using it in simple throwaway code is a bad habit that will catch up to you someday.
The reason std (as well as others) is short and not standard is so that prefixing it items from the standard library is not burdensome.
std::cout << text << " "; // not hard.
std::cout << std::endl;
There is no real reason to use std::endl (debugging being an exception I suppose). In normal situations the extra flush it adds will generally cause the output to slow down perceptibly. So prefer to use '\n' unless you specifically want to force a flush.
The problem here is, your code compares pointers, instead of comparing strings (as noted also in the other answer):
if(text == "//n")
{
...
}
Here text is a pointer (actually, an array of char, but in this context it's equivalent to a pointer), and "//n" also is a pointer (also an array). Comparing two pointers is not what you want.
To fix your code so it compares strings, one of the things your code compares should be a string instead of a pointer. To mark "//n" as a string, append s to it:
if(text == "//n"s)
{
...
}
This is a bit obscure; another solution is to make text a string (as described in the other answer):
std::string text;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I can't seem to come up with a chunk of code that traps the user until it gets a positive int and prompts the user appropriately if the user accidentally types a character or random garbage like "-1-3-4-39-32xfi3/". I just need a neat failproof cin loop structure and can't figure it out. Thanks.
I'm just wondering what other people do regarding console input to make draw ideas from that..how you get around bad input.
Do this:
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
int main()
{
for (std::string line; std::getline(std::cin, line); )
{
std::istringstream iss(line);
unsigned int n;
if (!(iss >> n >> std::ws) || iss.get() != EOF)
{
std::cout << "Bad input ('" << line << "'), ignoring.\n";
continue;
}
std::cout << "Success! We read: " << n << "\n";
return EXIT_SUCCESS;
}
std::cout << "Premature end of input!\n";
return EXIT_FAILURE;
}
In other words, continue reading input from the user until you are able to parse the input as the kind of data you want. I chose line-based processing, which is often the most natural, but any notion of "record" that you can skip if it isn't right will do. Note that it's possible the program never succeeds, namely if the user refuses to provide any good input.
I typically read an entire line with std::getline, then attempt to convert it to an integer with strtol. If the result is less than 0, they typed a leading -. strtol returns a pointer to the first character of input that couldn't be converted as an integer, so if it points to anything but \0, you know the user typed in something that couldn't be converted.
I really should switch to using std::stoi instead of strtol though. It supports pretty much the same capabilities, but its input is a std::string instead of a C-style string like strtol uses. I only continue to use strtol out of long habit, not because it's really a better solution.
Depending on what you have available, and how you want to respond to bad input, another possibility to consider would be boost lexical_cast. This throws an exception if it can't convert the entire input to the target type, so if you want an exception it may be more convenient (but if you don't want exceptions, it'll probably just cause you extra work).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Every time I use ifstream for input to my program for large inputs, I get something weird. I have a feeling this has to do with integer overflow, but my program still doesn't work with unsigned long long. Here is a simplified version of my code that still exhibits the error:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ofstream fout ("namenum.out");
ifstream fin ("namenum.in");
unsigned long long serial;
fin >> serial;
ifstream myReadFile;
cout << serial << endl;
return 0;
}
Here is the strange input (or larger inputs):
5747867437
Here is the output I get from cout:
1452900141
I have no idea what is causing this. Any help would be awesome.
Here is advice I have hardly given ever before: always check your inputs after you attempted to read (it feels, I have given this advice only a few thousands times so it is easy to miss). The stream can't predict what you are going to read and make sure it will work:
if (fin >> searial) {
fout << serial << '\n';
}
else {
std::cerr << "failed to read the value\n";
}
Looking at your code, I'd be about 100% certain that either the file failed to open (i.e. the stream is in bad state prior to the attempt to read) or the claimed content isn't in the file.
First of all, the number you supplied is certainly within the limit of unsigned long long.
Second, using >> for unsigned long long requires C++ 11 support. C++0x supports unsigned long.
I copied your code and made a file called "namenum.in", typed "5747867437" into "namenum.in" using UTF8 encoding.
Then the output is exactly 5747867437.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am trying to display image from different locations. There are car, airplane, chair etc. files need to be display. I put those words (car, airplane) in a text file. I can read words but when I put them in sprintf, I get nonsense characters.
I can display the words with cout<<*j<<endl;. But cout<<filename<<endl; gives me weird result.
string words;
std::vector<string>list;
fstream file;
file.open("h.txt");
while(!file.eof())
{
file >> words;
list.push_back(words);
}
for(vector<string>::iterator j=list.begin(); j!=list.end(); j++)
{
cout<<*j<<endl;
for(i=1; i<5; i++)
{
sprintf( filename,"D:\\101_ObjectCategories\\%s\\image_%04d.jpg",*j,i);
cout<<filename<<endl;
The C function sprintf() is oblivious of the C++ classes. If you really want to print a std::string using sprintf() you'll need to extract a C string:
sprintf(filename, "D:\\101_ObjectCategories\\%s\\image_%04d.jpg", j->c_str(), i);
You should also use snprintf() together with the size of the buffer you pass as filename to prevent overflow. Personally, I wouldn't really bother and rather using std::ostringstream in the first place:
std::ostringstream out;
out << "D:\\101_ObjectCategories\\" << *j << "\\image_"
<< std::setfill('0') << std::setw(4) << i << ".jpg";
std::string filename = out.str();
(after including <sstream> and <iomanip>).
Use must use *j.c_str():
sprintf( filename,"D:\\101_ObjectCategories\\%s\\image_%04d.jpg",*j.c_str(),i);
Otherwise, the string class itself is cast into a char* explicitly which is garbage of course :)
This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 8 years ago.
In c++, how can I iterate through each line in a string? There have been plenty of questions regarding reading a file line by line, but how can I do this with a std::string?
For example, if I have the following string:
1051
2232
5152
3821
0021
3258
How would I iterate through each number?
In c++, you can use string exactly as files, using the classes defined in the sstream header:
#include <sstream>
//...
std::string str=...; // your string
std::istrstream in(str); // an istream, just like ifstream and cin
std::string line;
while(std::getline(in,line)){
//do stuff with line
}
This is a bit simplistic, but you get the idea.
You can use in just as you would use cin, e.g. in>>x etc. Hence the solutions from How do I iterate over cin line by line in C++? are relevant here too - you might want to look at them for the "real" answer (just replace cin with your own istream
Edit:
As a side note, you can create strings in the same way you print to the screen, using the ostream mechanism (like cout):
std::ostringstream out;
out << header << "_" << 3.5<<".txt";
std::string filename=out.str();
Use a tokenizer and let '\n' or '\r\n' or the appropriate newline for your OS be the token splitter..
Or if you were using a buffered file stream reader, just create a stringstream from this new string and read from the string stream instead of the file stream.
In short nothing changes except that you aren't reading from a file.
A horribly naive solution would be to make a string stream from this and assign ints or strings in a while loop from it.