Sprintf with string [closed] - c++

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 :)

Related

Convert text (words) to integer [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
So I was making guessing game to learn something (I'm a beginner) and at the start I faced the problem that I didn't know how to do rng or something like that so I came up with idea where I just ask user to give his name and something he hates and I need to make this input somehow change to number (any kind except binary).
So in short I need a way to change any inputted text (string) to any integer number.
Here is an example of how to use a hash function, that already exists for the standard library.
#include <cstdio>
#include <string>
#include <iostream>
#include <functional>
int main() {
std::cout << "Starting Process!" << std::endl;
std::cout << "Enter Name: ";
std::string name;
std::cin >> name;
std::hash<std::string> hash_fn;
size_t str_hash = hash_fn(name);
std::cout << str_hash << '\n';
return 0;
}
I would suggest you to take a look at the "random" library if you want rng or to use hashing as other suggested.
If you want to generate yourself pseudo-random numbers from an input string, you could do the following:
To acces a character, you could use the [ ] operator, something like that:
std::string str = "The Name";
str[index]; // to acces a character
Cast the characters into integers to work with them. Keep in mind that every character has an ASCII value, so you could do something like this:
static_cast<int>(str[2]);
Now you have accesed the third character, according to the string above, 'e'. Which happens to be 101 when transformed into an int (remember, the ASCII value).
You can then create some algorithm using that.

Converting char to string in c++ [closed]

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";

Having lots of trouble using cin robustly in C++ [closed]

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).

Everytime I read in through ifstream for a specific input, the input changes, possible int overflow [closed]

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.

Finding the line that has the most words and output it to text file. C++ [closed]

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
So I have a file with like 5-6 lines of text, and I need to find which one has the most words and output it into another file. Any of you have suggestions?
I'm not that advanced in C++, I' using classes, arrays, no vectors or such.
Other code is rather irrelevant in my program, but if you need it i'll paste it here.
EDIT: http://pastebin.com/zh7HPCtT here's my code, the first part of it finds how many words in a line are longer than the first word.
I haven't added anything else for the other half of the assignment.
Try this:
read each line
count the words in it
if it has more words than any other line you've seen, save it
after the file is exhausted, print the saved line
One of the simplest solutions is to use a string max that you will use in your loop.
Then you loop over all lines in your file, and for each line line you compare the number of words in line against the number of words in max, and if line has more words, assign it to max.
After you have done that for all lines, open a file or just dump to standard output (enabling your user to redirect your output to some file itself), and print max.
The core algorithm is very much like finding the maximum of two numbers, and in fact you can just use std::max from the standard library, with your own comparator.
Just for fun, here's a very suboptimal solution:
#include <algorithm>
#include <sstream>
#include <string>
#include <iostream>
std::string longest_phrase (std::istream &is) {
std::string longest, current_line;
while (getline(is, current_line))
longest = max(longest, current_line, [] (std::string const &lhs, std::string const &rhs) {
std::stringstream lhss(lhs), rhss(rhs);
std::string sink;
int words_lhs = 0, words_rhs = 0;
while (lhss >> sink) ++words_lhs;
while (rhss >> sink) ++words_rhs;
return words_lhs < words_rhs;
});
return longest;
}
std::string longest_phrase (std::string const &content) {
std::istringstream ss(content);
return longest_phrase(ss);
}
int main () {
std::cout << longest_phrase("Hello, I am a cat!\n"
"Hello, I am an unhappy bear!\n"
"Pardon?!\n"
"WtfOMG!?=§\"$%&/!!?µ€#+%$§==!!!") << '\n';
}
It will output Hello, I am an unhappy bear!\n. There's a lot of resource waste and you should make it more stateful, but it will serve you as a starting point.