I have the following code:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream os;
char fileName[] = "0.txt";
for(int i = '1'; i <= '5'; i++)
{
fileName[0] = i;
os.open(fileName);
os << "Hello" << "\n";
os.close();
}
return 0;
}
The aim is to write my code output into multiple .txt files up to, say 64 different times. When I change this loop to run more than 10, that is
for(int i = '1'; i <= '10'; i++)
I get the following error:
warning: character constant too long for its type
Any ideas how to write to more than 10 files? Moreover, how do I write a number after each "Hello", e.g. "Hello1 ... Hello10"?
Cheers.
I believe the reason you receive that warning is because you're attempting to assign two chars into one slot of the char array:
fileName[0] = i;
because when i = 10;, it's no longer a single character.
#include <fstream>
#include <iostream>
#include <string>//I included string so that we can use std::to_string
using namespace std;
int main() {
ofstream os;
string filename;//instead of using a char array, we'll use a string
for (int i = 1; i <= 10; i++)
{
filename = to_string(i) + ".txt";//now, for each i value, we can represent a unique filename
os.open(filename);
os << "Hello" << std::to_string(i) << "\n";//as for writing a number that differs in each file, we can simply convert i to a string
os.close();
}
return 0;
}
Hopefully this resolved the issues in a manner that you're satisfied with; let me know if you need any further clarification! (:
Related
As simple as it sounds. I'm a newb when it comes to c++, but I have been following cpp reference and some online tutorials to write code. My code should output a string as "SuCh", but instead it outputs something as "SSuuCChh". Is there a practical error I'm missing?
#include <cctype>
#include <iostream>
using namespace std;
int main()
{
string mani;
int L = 0;
getline(cin, mani);
for (int i = 0; i<mani.length();i++){
if(mani.at(i) == ' '){
cout << ' ' << flush;
L = L - 2;
} else if(L%2==0){
putchar(toupper(mani.at(i)));
L++;
} else if(L%1==0) {
putchar(tolower(mani.at(i)));
L++;
}
}
return 0;
}
You're calling putchar and using cout, so you're printing each character twice in two different ways.
Eliminate either the call to putchar(), or the cout <<, and you will only get each character once.
From cplusplus's putchar(int) reference:
int putchar ( int character );
Write character to stdout.
It is equivalent to calling putc with stdout as second argument.
So your code should look more like
#include <cctype>
#include <cstdio>
#include <iostream>
#include <string>
int main(void) {
std::string mani, F;
getline(std::cin, mani);
for(int i = 0; i < mani.length; i++) {
if(i % 2 == 0) {
std::cout << std::toupper(mani.at(i));
} else {
std::cout << std::tolower(mani.at(i));
}
}
std::cout << std::endl;
return 0;
}
Note: Extra includes of and are there to ensure those types are included. They may be able to be removed, however I would leave them. Plus, dropping the std prefix can be dangerous due to certain popular libraries, such as Boost, defining their own versions of the functions and objects.
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream infile; // ifstream is reading file
infile.open("read.txt"); // read.txt is the file we need to read
std::cout << infile;
string str;
if (infile.is_open()) {
while (getline(infile, str)) {
char str[2000], ch;
int i, j, len;
len = strlen(str);
for (i = 0; i < len; i++) {
for (j = 0; j < (len - 1); j++) {
if (str[j] > str[j + 1]) {
ch = str[j];
str[j] = str[j + 1];
str[j + 1] = ch;
}
}
}
}
cout << "\nProcessed data:" << str;
}
return 0;
}
My txt file:
Today is a fine day.
It’s sunny.
Let us go out now!
My result should be:
.Taaaddefiinosyy
’.Innsstuy
!Legnooosttuuw
Spaces is consider here as well.
I'm new to C++.
I need some pros help.
Thank you very much!
Making use of the STL:
Read your file line by line into a std::string using std::getline.
Sort every line using std::ranges::sort.
Print it.
The example below:
also uses the fmt library instead of std::cout, and
reads from a std::istringstream instead of a std::ifstream.
[Demo]
#include <algorithm> // sort
#include <fmt/core.h>
#include <sstream> // istringstream
#include <string> // getline
int main() {
std::istringstream iss{
"Today is a fine day.\n"
"It's sunny.\n"
"Let us go out now!\n"
};
fmt::print("Original file:\n{}\n", iss.str());
fmt::print("Processed file:\n");
std::string line{};
while (std::getline(iss, line)) {
std::ranges::sort(line);
fmt::print("{}\n", line);
}
}
// Outputs:
//
// Original file:
// Today is a fine day.
// It's sunny.
// Let us go out now!
//
// Processed file:
// .Taaaddefiinosyy
// '.Innsstuy
// !Legnooosttuuw
Your code does not work, because:
The line std::cout << infile; is wrong. If you want to print the result of istream::operator bool() in order to determine whether the file was successfully opened, then you should write std::cout << infile.operator bool(); or std::cout << static_cast<bool>(infile); instead. However, it would probably be better to simply write std::cout << infile.fail(); or std::cout << !infile.fail();.
The function std::strlen requires as a parameter a pointer to a valid string. Maybe you intended to write str.length()? In that case, you should delete the declaration char str[2000], because it shadows the declaration string str;.
You should print the sorted result immediately after sorting it, before it gets overwritten by the next line. Currently you are only printing the content str a single time at the end of your program, so you are only printing the last line.
After performing the fixes mentioned above, your code should look like this:
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream infile; // ifstream is reading file
infile.open("read.txt"); // read.txt is the file we need to read
std::cout << infile.fail();
string str;
if (infile.is_open()) {
while (getline(infile, str)) {
char ch;
int i, j, len;
len = str.length();
for (i = 0; i < len; i++) {
for (j = 0; j < (len - 1); j++) {
if (str[j] > str[j + 1]) {
ch = str[j];
str[j] = str[j + 1];
str[j + 1] = ch;
}
}
}
cout << "\nProcessed data:" << str;
}
}
return 0;
}
For the input
Today is a fine day.
It's sunny.
Let us go out now!
this program has the following output:
0
Processed data: .Taaaddefiinosyy
Processed data: '.Innsstuy
Processed data: !Legnooosttuuw
Note that the input posted in your question contains a forward tick ’ instead of an apostrophe '. This could cause trouble. For example, when I tested your program, this forward tick was encoded into a multi-byte UTF-8 character, because it is not representable in 7-bit US-ASCII. This caused your sorting algorithm to fail, because it only supports single-byte characters. I was only able to fix this bug by replacing the forward tick with an apostrophe in the input.
Here is part of my code:
//num is an int
string s = "" + num;
When I run this in Xcode on a Macbook, s will be assigned to a strange string.
Can any one explain this to me?
I am really confused.
Thanks.
I assume string refers to the std::string type, declared in the standard header <string>. You haven't given that as context - technically, from information you have given it could be some preceding typedef or a macro.
The explanation as to why
string s = "" + num;
gives a "strange string" is that "" is represented in memory as a const array of one char that has the value zero. In the expression "" + num, the "" is converted to a pointer (equal to the address of that char with value zero), and + num then gives the address of some location in memory, num characters after.
If num is non-zero, that memory address may not exist, or (if it exists) might contain arbitrary data.
In any event, that pointer is passed to the constructor of std::string (in order to construct s). That constructor starts at the address given, and keeps copying data into the std::string until it happens to find a character with value zero. The characters in between could be anything - they are whatever happens to be at that memory location.
Formally, the C++ standard describes all this (accessing data via a bad pointer) as undefined behaviour. That means the C++ standard says nothing about what result is permitted, so any result is allowed. It could result in strange data in your string. The operating system might detect your program accessing memory it shouldn't, and forceably terminate your program. It could reformat your hard drive and reinstall your operating system.
Assuming you just want to write num to a string (e.g. num with value 42 results in a string like "42"), then the usual technique is to convert num to a std::string. For example;
std::string s = to_string(num); // C++11 or later
or
#include <sstream> // pre_C++11 (albeit valid in C++11)
std::ostringstream ostr;
ostr << num;
std::string s(ostr.str());
string s = std::to_string(num);
Try this one.
The idea about std::to_string() is good, but it unfortunately only works with C++11 and I have seen compilers that do not fully support that aspect though they support C++11. If you can use it, use it.
If it does not work try this:
#include <sstream>
...
int num = 5;
float rNum = 63.2;
std::stringstream ss;
ss << num;
ss << rNum;
std::string s;
ss >> s;
cout << s << endl;
You are going to get the float and int values formatted to one string. Actually I think you are better off with stringstreams if you have multiple variables get formatted. Pull them out as string with ss >> s and you are done!
The reason you were getting undesirable answer is the arithmetic addition of num to the empty string s, which is basically like pointer addition in C language.
See the examples for better explanation:
Eg. 1:
#include <iostream>
#include <string>
using namespace std;
int main() {
int num = 0;
string s = "1234567890" + num;
cout << s << endl;
return 0;
}
OUTPUT: 1234567890
Eg. 2:
#include <iostream>
#include <string>
using namespace std;
int main() {
int num = 1;
string s = "1234567890" + num;
cout << s << endl;
return 0;
}
OUTPUT: 234567890
Eg. 3:
#include <iostream>
#include <string>
using namespace std;
int main() {
int num = 4;
string s = "1234567890" + num;
cout << s << endl;
return 0;
}
OUTPUT: 567890
Eg. 4:
#include <iostream>
#include <string>
using namespace std;
int main() {
int num = 8;
string s = "1234567890" + num;
cout << s << endl;
return 0;
}
OUTPUT: 90
so on..
Since, here the string s is empty and the num has garbage value which leads to undefined result.
Better use to_string() before appending num to the empty string s.
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
int num = 1000;
string s = "" + to_string(num);
cout << s << endl;
return 0;
}
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
int main(int argc, char* argv[])
{
ifstream ifile;
char fName[30][30];
long int uTime[30][10];
ifile.open("sync.log");
char ch;
string str = "";
if(ifile.fail())
{
cout<<"Invalid File Name!";
system("pause");
exit(1);
}
int i = 0;
while(!ifile.eof())
{
getline(ifile, str);
cout<<str<<endl;
sscanf(str.c_str(),"%ld %[^\n]",&uTime[i],fName[i]);
i++;
str = "";
}
ifile.close();
system("pause");
cout<<"Output:"<<endl;
for(i = 0 ; i < 2 ; i ++)
{
cout<<uTime[i]<<" ";
cout<<fName[i];
cout<<endl;
}
getch();
return 0;
}
File : sync.log
Format:
1399865017 Test1.txt
1399865017 Test1.txt
so here is my full code and i have sync.log file in root directory where the VC++ saved the projects...
It must be stored like this in array after Reading from File
uTime[0] = 1399865017;
fName[0] = "Test1.txt";
fName[1] = "Test1.txt";
with this above code i am getting
uTime[0] = 0012F6B0 and fName[0] = "Test1.txt"
and i want this uTime[0] = 1399865017;
fName[0] = "Test1.txt";
I think you meant to use:
long int uTime[30];
instead of
long int uTime[30][10];
With that, the line that reads data into uTime and the line that write uTime to cout would make sense.
Given that you have:
long int uTime[30][10];
when you do:
cout << uTime[i] << …
you are printing a pointer to an array of 10 long. That pointer is formatted in hex; that is why you are getting hex output.
You need to fix the sscanf() call — you've got a bogus argument of &uTime[i] there — and the output too. Since it is not clear why uTime is a 2D array, it isn't easy to tell you how to fix it, but the simplest solution would be to drop the [10] from the array definition.
Ok guy i had to make a program to split elements of a string. And after that print those words.
there are some problems i am facing:
1) the array prints more than the size of the words in string i want that it should end printing as soon as last word is printed. i tried to prevent that but it always gives runtime error when i try to break at the last word.
2)is there any other efficient way to split and print ???
#include <sstream>
#include <iostream>
#include<cstdio>
#include<cstdlib>
#include <string>
using namespace std;
int main()
{
std::string line;
std::getline(cin, line);
string arr[1000];
int i = 0;
int l=line.length();
stringstream ssin(line);
while (ssin.good() && i < l)
{
ssin >> arr[i];
++i;
}
int size = sizeof(arr) / sizeof(arr[0]);
for(i = 0; i <size; i++){
cout << arr[i] << endl;
}
return 0;
}
int size = sizeof(arr) / sizeof(arr[0]);
That is a compile time value, and it's always going to be the number of elements in your array (1000). It has no idea how many strings you assigned to in your loop. You stored the number of successfully read strings (plus 1) in the i variable, so you could do this instead:
int size = i - 1;
But if it were up to me, I would just use a growable structure, like vector (#include <vector>)
std::vector<std::string> arr;
std::string temp;
while (ssin >> temp)
{
arr.push_back(temp);
}
for (auto const & str : arr)
{
std::cout << str << std::endl;
}
/* If you're stuck in the past (can't use C++11)
for (std::vector<std::string>::iterator = arr.begin(); i != arr.end(); ++i)
{
std::cout << *i << std::endl;
}
*/
For general purpose character based splitting, I would much prefer boost::split (I know you can't use it, but for future reference)
std::vector<std::string> arr;
boost::split(arr, line, boost::is_any_of(".,;!? "));
Read up on the function strtok. It is old school but very easy to use.
1) there are a couple of changes you should make to your program:
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string line("hello string world\n");
string arr[1000];
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 1000)
{
ssin >> arr[i++];
}
int size = i-1;
for(i = 0; i < size; i++){
cout << i << ": " << arr[i] << endl;
}
return 0;
}
namely, you don't want to print sizeof(arr)/sizeof(arr[0]) (i.e. 1000) elements. There is no point in the condition i < l
2) stringstream is fine if you just want to separate the single strings; if more is needed, use boost/tokenizer for splitting strings. It's modern c++, once you try it you'll never come back!
this is the best method i think no worry now
#include <sstream>
#include <iostream>
#include<cstdio>
#include<cstdlib>
#include <cstring>
#include <string>
using namespace std;
int main ()
{
std::string str;
std::getline(cin, str);
string arr[100];
int l=0,i;
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
// cstr now contains a c-string copy of str
char * p = std::strtok (cstr,".,;!? ");
while (p!=0)
{
//std::cout << p << '\n';
arr[l++]=p;
p = strtok(NULL,".,;!? ");
}
for(i = 0; i <l; i++)
{
cout << arr[i] << endl;
}
delete[] cstr;
return 0;
}