Im working on a college project and it requires big number like 43,000,000 but everytime i launch the program it gives me something like this 43000,000. I already used std::fixed and precision but it doesnt add the second comma.
this is the code:
double PreEnCol() {
if (marca == 1)
return (105.000*562);
else if (marca == 2)
return (65.000*562);
else if (marca == 3)
return (54.000*562);
else if (marca == 4)
return (125.000*562);
else if (marca == 5)
return (129.000*562);
else if (marca == 6)
return (85.900*562);
}
string toString(){
stringstream s;
s << endl;
s << std::fixed << std::setprecision(1) << "Precio en colones: "<<PreEnCol() << endl;
return s.str();
}
Please i need help with this i've been dealing with this problem for hours.
Mostly your output depend on your default locale. You need to override you whole locale OR part of locale of you interest.
Below code helps you to override part of locale which is responsible for printing commas in number.
#include <iostream>
#include <sstream>
#include <iomanip>
#include <locale>
struct Sep3Digit : std::numpunct<char> {
std::string do_grouping() const { return "\003"; }
};
std::string FormatWithCommas(double d)
{
std::stringstream ss;
ss.imbue(std::locale(std::cout.getloc(), new Sep3Digit));
ss << std::fixed << d;
return ss.str();
}
int main()
{
std::cout<<FormatWithCommas(std::numeric_limits<double>::max())<<std::endl;
return 0;
}
You can usually do that with default system locale:
#include <locale>
string toString(){
stringstream s;
s << endl;
s.imbue(std::locale("")); // <-- set locale. OR: std::locale("en_US")
s << std::fixed << std::setprecision(1) << "Precio en colones: "<<PreEnCol() << endl;
return s.str();
}
Note that this will print 43000000 as 43,000,000 in some parts of the world, or as 43.000.000 in others where '.' is used as grouping separator.
Here's full example:
#include <locale>
#include <string>
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
string toString(int n)
{
stringstream s;
s << endl;
s.imbue(std::locale("")); // <-- set locale
s << std::fixed << std::setprecision(1) << "Precio en colones: "<< n << endl;
return s.str();
}
int main()
{
int n = 43000000;
cout << "formatted " << n << ": " << toString(n) << endl;
}
It produces this output:
formatted 43000000:
Precio en colones: 43,000,000
Related
I'm currently making a basic program design to behave somewhat like a chell. The code is here:
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <Windows.h>
#include <Stdio.h>
#include <string>
using namespace std;
main()
{
SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE),10);
std::string name;
std::string pass;
std::string msg;
int x = 1;
srand(time(0));
cout << "Booting up system..." << endl;
cout << "Serial Code: " << (rand()%1000) << "." << endl;
cout << "Username: ";
std::getline(std::cin, name);
cout << "Password: ";
std::getline(std::cin, pass);
cout << "" << endl;
while (true)
{
cout<<x<<": ";
std::getline(std::cin, msg);
x += 1;
if (msg == "Hello!"){
cout << "Hi!" << endl;
}
if (msg == ""){
cout << "[No Text Inserted]" << endl;
}
system ("pause");
}
And, if no text is input it displays:
1:
[No Text Inserted]
How do I get this output?
1: [No Text Inserted]
Thank you in advance!
-DJ
In your if statements, store the string into a variable and print out in the end. Also if you're comparing the same variable, I recommend using if else statements. It makes it more readable. So:
string output;
if (msg == "Hello!)
{
output = "Hi!";
}
else if (msg == "")
{
output = "[No Text Inserted]";
}
output = x.str() + ": " + output;
cout << output << endl;
Try that out and let me know if that works.
What you could do is remember input cursor position and if the input is empty string, go back to that position and print your fail message, something like this:
#include <iostream>
#include <string>
#include <windows.h>
int main()
{
HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
std::string input;
std::cout << "Enter something: ";
// remember cursor position
CONSOLE_SCREEN_BUFFER_INFO info;
COORD inputPos = GetConsoleScreenBufferInfo(conout, &info) ? info.dwCursorPosition : COORD{ 0, 0 };
if (!std::getline(std::cin, input) || input.empty())
{
SetConsoleCursorPosition(conout, inputPos);
std::cout << "[No Text Inserted]" << std::endl;
}
}
Is there a way to configure ostream using iomanip to output floating point numbers as follows:
0.00000000000000E+0000
3.99147034531211E-0003
...
I am translating code from pascal to C++ and I need to output numbers in exactly same format. It is preferable to use std::ofstream instead of fprintf or other C library functions.
One way to do this is with some string manipulation. Format to a stringstream using scientific notation, then split the string on the 'e'. Now you have the parts you can format yourself.
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
std::string format(double val)
{
std::ostringstream oss;
oss << std::scientific << std::setprecision(14) << val;
auto result = oss.str();
auto match = result.find('e');
if (match == std::string::npos)
{
// Should never get here -- maybe throw
}
oss.str("");
auto exp = std::stoi(result.substr(match+1));
oss << result.substr(0, match) << 'E'
<< std::setw(5) << std::setfill('0')
<< std::internal << std::showpos << exp;
result = oss.str();
return result;
}
int main()
{
std::cout << format(3.99147034531211e-3) << '\n';
std::cout << format(6.02214085774e23) << '\n';
}
Output:
3.99147034531211E-0003
6.02214085774000E+0023
You will need to use std::fixed
Sample program:
#include <iostream>
#include <fstream>
int main()
{
float f1 = -187.33667, f2 = 0.0;
std::ofstream out("test.bin",std::ios_base::binary);
if(out.good())
{
std::cout << "Writing floating point number: " << std::fixed << f1 << std::endl;
out.write((char *)&f1,sizeof(float));
out.close();
}
std::ifstream in("test.bin",std::ios_base::binary);
if(in.good())
{
in.read((char *)&f2,sizeof(float));
std::cout << "Reading floating point number: " << std::fixed << f2 << std::endl;
}
return 0;
}
OP by user Texan40. For more info: Here
User inputs a string in form of
length=10 width=15
The task is to find the length's and width's value in such a string(and assign them to variables). So, how can I find those two numbers? What functions/methods should I use? Can you guys just give me an idea?
Regular expressions are fun and are usually not acceptable as homework solutions for introductory classes.
match[1] and match[2] are the numerical portion of the string that you are interested in. You'll probably want to pass them to stoi() if you need to manipulate them as integers.
Code
#include <iostream>
#include <regex>
int main() {
std::string s("length=10 width=15");
std::regex re("length=([0-9]+) width=([0-9]+)");
std::smatch match;
if (regex_match(s, match, re)) {
std::cout << "length: " << match[1] << "\n";
std::cout << "width: " << match[2] << "\n";
}
}
Output
length: 10
width: 15
use stringstream:
#include <string>
#include <iostream>
#include <sstream>
#include <map>
using namespace std;
int main()
{
stringstream ss;
ss.str("length1=10 width=15 length2=43543545");
map<string, int> resMap;
string key;
int val;
while (ss.peek() != EOF) {
if (isalpha(ss.peek())) {
char tmp[256];
ss.get(tmp,streamsize(256),'=') ;
key = tmp;
} else if (isdigit(ss.peek())) {
ss >> val;
resMap.insert(pair<string, int>(key,val));
} else {
ss.get();
}
}
cout << "result:\n";
for (map<string, int>::iterator it = resMap.begin(); it != resMap.end(); ++it) {
cout << "resMap[" << it->first<< "]=" << it->second << endl;
}
getchar();
return 0;
}
I've almost finished writing a program that will detect palindromes from a file and output a new file highlighting the palindromes but I'm stuck on a really dumb error. I'm trying to write a test for one of my methods (TDD) and, for some reason, it's not recognizing the function as within the scope.
I'm calling the isPalindrome(string s) method (declared in PalindromeDetector.h) in my isPalindromeTest() method (declared in PalindromeDetectorTest.h) but, for some reason, it's not recognizing it as within the scoope.
I feel like everything should be working but it just isn't. Any help you can provide would be greatly appreciated. Below is my code:
PalindromeDetector.h
#ifndef PALINDROMEDETECTOR_H_
#define PALINDROMEDETECTOR_H_
#include <iostream>
using namespace std;
class PalindromeDetector {
public:
void detectPalindromes();
bool isPalindrome(string s);
};
#endif /* PALINDROMEDETECTOR_H_ */
PalindromeDetector.cpp
#include "PalindromeDetector.h"
#include "Stack.h"
#include "ArrayQueue.h"
#include <iostream>
#include <fstream>
#include <cassert>
#include <cctype>
#include <string>
using namespace std;
void PalindromeDetector::detectPalindromes() {
cout << "Enter the name of the file whose palindromes you would like to detect:" << flush;
string fileName;
cin >> fileName;
cout << "Enter the name of the file you would like to write the results to: " << flush;
string outFileName;
cin >> outFileName;
fstream in;
in.open(fileName.c_str());
assert(in.is_open());
ofstream out;
out.open(outFileName.c_str());
assert(out.is_open());
string line;
while(in.good()){
getline(in, line);
line = line.erase(line.length()-1);
if(line.find_first_not_of(" \t\v\r\n")){
string blankLine = line + "\n";
out << blankLine;
} else if(isPalindrome(line)){
string palindromeYes = line + " ***\n";
out << palindromeYes;
} else {
string palindromeNo = line + "\n";
out << palindromeNo;
}
if(in.eof()){
break;
}
}
in.close();
out.close();
}
bool PalindromeDetector::isPalindrome(string s){
unsigned i = 0;
Stack<char> s1(1);
ArrayQueue<char> q1(1);
while(s[i]){
char c = tolower(s[i]);
if(isalnum(c)){
try{
s1.push(c);
q1.append(c);
} catch(StackException& se) {
unsigned capS = s1.getCapacity();
unsigned capQ = q1.getCapacity();
s1.setCapacity(2*capS);
q1.setCapacity(2*capQ);
s1.push(c);
q1.append(c);
}
}
i++;
}
while(s1.getSize() != 0){
char ch1 = s1.pop();
char ch2 = q1.remove();
if(ch1 != ch2){
return false;
}
}
return true;
}
PalindromeDetectorTest.h
#ifndef PALINDROMEDETECTORTEST_H_
#define PALINDROMEDETECTORTEST_H_
#include "PalindromeDetector.h"
class PalindromeDetectorTest {
public:
void runTests();
void detectPalindromesTest();
void isPalindromeTest();
};
#endif /* PALINDROMEDETECTORTEST_H_ */
PalindromeDetectorTest.cpp
#include "PalindromeDetectorTest.h"
#include <cassert>
#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
using namespace std;
void PalindromeDetectorTest::runTests(){
cout << "Testing palindrome methods... " << endl;
detectPalindromesTest();
isPalindromeTest();
cout << "All tests passed!\n" << endl;
}
void PalindromeDetectorTest::detectPalindromesTest(){
cout << "- testing detectPalindromes()... " << flush;
fstream in;
string fileName = "testFile.txt";
in.open(fileName.c_str());
assert(in.is_open());
cout << " 1 " << flush;
ofstream out;
string fileOutName = "testFileOut.txt";
out.open(fileOutName.c_str());
assert(out.is_open());
cout << " 2 " << flush;
cout << " Passed!" << endl;
}
void PalindromeDetectorTest::isPalindromeTest(){
cout << "- testing isPalindrome()... " << flush;
// test with one word palindrome
string s1 = "racecar";
assert(isPalindrome(s1) == true); // these are not recognized within the scope
cout << " 1 " << flush;
// test with one word non-palindrome
string s2 = "hello";
assert(isPalindrome(s2) == false); // these are not recognized within the scope
cout << " 2 " << flush;
// test with sentence palindrome
string s3 = "O gnats, tango!";
assert(isPalindrome(s3) == true); // these are not recognized within the scope
cout << " 3 " << flush;
// test with sentence non-palindrome
string s4 = "This is not a palindrome.";
assert(isPalindrome(s4) == false); // these are not recognized within the scope
cout << " 4 " << flush;
cout << " Passed!" << endl;
}
isPalindrome is a member function of PalindromeDetector, but you are trying to call it from within a PalindromeDetectorTest method. If the test class derived from PalindromeDetector this would work, but there isn't (and almost certainly shouldn't be) any such relationship between them.
You need a PalindromeDetector object to call the method on. Probably just as simple as this:
void PalindromeDetectorTest::isPalindromeTest(){
cout << "- testing isPalindrome()... " << flush;
PalindromeDetector sut; // "subject under test"
// test with one word palindrome
string s1 = "racecar";
assert(sut.isPalindrome(s1) == true);
// etc.
}
You could also make the PalindromeDetector methods static since the object doesn't appear to have any state. Then you could simply call PalindromeDetector::isPalindrome(s1); without the need to create an instance.
For some reason it skips over the first input an goes straight to the second one.
#include<iostream>
#include<string>
using namespace std;
int stringWork()
{
const int LENGTH = 40;
char firstString[LENGTH], secondString[LENGTH];
cout << "Enter First String: ";
//it skips over this following line
cin.getline(firstString, LENGTH);
cout << "Enter Another String: ";
cin.getline(secondString, LENGTH);
if (strcmp(firstString, secondString) == 0)
cout << "You entered Same string two times\n";
else
cout << "The two strings you entered are not the same\n";
system("pause");
return 0;
}
int main()
{
stringWork();
return 0;
}
it only allows input for one string
This piece of code works on my machine just fine. However, please do change #include <string> to #include <string.h> or #include <cstring>, and add #include <stdlib.h> or #include <cstdlib>.
Fix the code like this:
#include <iostream>
#include <string>
void stringWork()
{
const int LENGTH = 40;
char firstString[LENGTH], secondString[LENGTH];
std::cout << "Enter First String: " << std::flush;
std::cin.getline(firstString, LENGTH);
std::cout << "Enter Another String: " << std::flush;
std::cin.getline(secondString, LENGTH);
if (strcmp(firstString, secondString) == 0) {
std::cout << "You entered Same string two times." << std::endl;
} else {
std::cout << "The two strings you entered are not the same." << std::endl;
}
}
int main()
{
stringWork();
return 0;
}
Some notes about my version of your code:
Please don't use using namespace std.
Use std::flush to flush the characters in the output stream. This is necessary because usually the characters are only flushed with std::endl or in some implementations if you add a newline character.
Avoid mixing C and C++ code as you did. Use the std::getline method to read a line directly into a std::string. Shown in the next example.
Please care about your code style, especially if you post it in the public.
A even better implementation would avoid any C code and use just C++:
#include <iostream>
#include <string>
void stringWork()
{
std::cout << "Enter First String: " << std::flush;
std::string firstString;
std::getline(std::cin, firstString);
std::cout << "Enter Another String: " << std::flush;
std::string secondString;
std::getline(std::cin, secondString);
if (firstString == secondString) {
std::cout << "You entered Same string two times." << std::endl;
} else {
std::cout << "The two strings you entered are not the same." << std::endl;
}
}