This is my code.
#include <iostream>
using namespace std;
int main()
{
string s;
cin >> s;
cout << s.length();
return 0;
}
why it gives output as 65535 even if i increase characters in s.
I have added the samle input here https://ideone.com/c2V8YX
The Ideone FAQ answers:
What is the size limit for the source code, input and output?
64 kB.
Note that this limitation has nothing to do with C++ language, or even the particular implementation of it. The limitation is by Ideone (and it's understandable. You wouldn't want to allow people to upload unlimited data to fill up your server). It appears that their behaviour is to silently truncate the input.
This is not exactly wonderful code but the general idea seems sound. Basically reading chunks and appending them (probably to a buffewr as opposed to a raw string) but ya get the idea
#include <iostream>
using namespace std;
int main() {
string all;
char snippet[100];
while(cin.get(snippet, 100)){ all += snippet; }
cout<< all.length() << '\n';
return 0;
}
Related
I'm trying to read in a picture file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream read("C://Users/Ben/Desktop/1.jpg");
while (1){
cout << read.get();
cin.get();
}
return 0;
}
When I do this, I get a series of numbers ranging from 0 ~ 255. So I'm assuming it's reading in the byte values correctly, except for the fact that I hit -1 (eof) prematurely. After about 30 to 40 values, the -1 appears. It's a 3MB file. I don't expect the -1 to appear until way later. What's going on?
As #melpomene mentioned in their comment there may be a difference for the results of std::ifstream::get() regarding the file was opened using the std::ios::binary mode or not (at least for the Windows OS it seems).
There's no evidence that a value of -1 as result of std::ifstream::get() indicates that the read stream is in std::ifstream::eof() state. You may read up in the std::ifstream::get() reference documentation, for more information.
Try this:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Add the mode ios::binary to make the file load in binary format.
ifstream read("C://Users/Ben/Desktop/1.jpg", ios::binary);
// Declare data variable
int data = 0;
// Reading loop
while (read.read((char*)&data, 4) && read.gcount() != 0) {
// Output data
cout << data << endl;
}
// Wait for user input before closing program
cin.get();
return 0;
}
I was asked to make a program that reads a cin could be text and then counts the words in it(i need to count as a word every name that can be accepted as a variable name ex _a,a1) my problem is that my code works for only one byte. if its more than one the sum is always 0.The only thing i think i can have wrong is that i didn't put the string into an array but a friend of mine told me i don't need to do so.below is my code:
#include<iostream>
#include<string>
#include<stdio.h>
using namespace std;
int main(){
int sum=0;
bool z= false; //z is just a switch to see if we are inside a word\n
string s;
cout<<"Insert text: ";
getline(cin,s); //here we get the string\n
int n=s.length()-1; //for some reason i==(s.length-1) put a warning$
for(int i=0;i==n;i++){ //here we check each byte to see what it contai$
cout<<s[i];
if(isalpha(s[i]) || s[i]=='_'){ //to enter a word we need a let$
z=true;
sum++;}
if(z==true){ // if we are in a word we can have numbers as w$
if(!isalnum(s[i]) && s[i]!='_'){
z=false;}} // exit the current word and go$
if(s[i]==EOF){ // the end\n
break;}}
cout<<"Number of words is: "<<sum<<endl; // the real end\n
return 0;
}
This is so much easier than the code you have provided. We can do this with the STL using an istream iterator. If you choose to use C++ and not C, then you should take advantage of the standard library.
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
int main(){
vector<string> words((istream_iterator<string>(cin)), istream_iterator<string>());
for(int i = 0; i < words.size(); i++)
cout << words[i] << '\n';
return 0;
}
Check your for loop.. it runs as long as the second statement is true.. when is it true that i==n? only at the very last byte.. change this to i<=n instead.
First of all you don't need dont use getline because it is insecure, use cin instead. Also you do not need the and use cin instead of getline. Also if getline is used with an array it could pose a serious problem and could be exploited via stack overflow. Sorry I cant help much what you were asking but I just wanted to give you a heads up.
I'm making a shift cipher that reads in text from a file and decodes it. The decryption works fine howver i can't figure out how to find the length of the file without hardcoding it into the size of the char array. It also only reads in one line, anything with a newline in corrupts.
Any help would be greatly appreciated, i've left out the main block of code as that deals with the array after it has been read in and seemed a bit long and irrelevant.
string fileName;
cout << "Please enter the locations of your encrypted text (e.g ""encryptedText.txt""): ";
getline( cin, fileName );
char encryptedMessage[446]; //How do i read in the file length and declare the array size as a variable instead of [446]?
char decryptedMessage[446];
ifstream in(fileName);
if(in.get(encryptedMessage, 446))
{
[my decrypting code]
}
else
{
cout << "Couldn't successfully read file.\n";
}
system("pause");
Well, a simple one-liner for reading a whole file into a dynamically sized array (don't use a statically sized array) of chars would be:
#include <vector>
#include <iterator>
std::vector<char> encryptedMessage(std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>());
Don't mess with dynamic allocation yourself, just let std::vector do its job. And due to its optimized growth behaviour you don't really need to bother with checking the file size. Optimize for speed when neccessary or at least not before your files get larger than a few hundred characters. And of course the istreambuf_iterator (instead of istream_iterator) doesn't handle whitespace any special, it just takes each character raw from the file one by one.
You may do the same with a std::string instead of a std::vector<char>, but I'm not sure about its growth behaviour (maybe it always reallocates the array with one more element). But then again, who cares for speed when the file contains 400 charcters?
You can use seekg to get the size of an entire file:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
long begin_byte, end_byte;
ifstream in("example.txt");
begin_byte = in.tellg();
in.seekg (0, ios::end);
end_byte = in.tellg();
int total_bytes = end_byte - begin_byte;
in.seekg(0, ios::begin);
char *message = new char[total_bytes + 1];
int index = 0;
while (in) {
message[index++] = in.get();
}
in.close();
cout << "message is: " << message << endl;
delete [] message;
return 0;
}
You can read more about seekg, tellg and files in c++ as a whole here.
However a better solution then using char * is using a std:string and calling push_back on it while in has not ended:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
ifstream in("example.txt");
string message;
while (in) {
message.push_back(in.get());
}
in.close();
cout << "message is: " << message << endl;
return 0;
}
You cannot have Variable Length Arrays(VLA) in C++.
Compilers do provide VLA's as extensions but using them would make your code non-portable.
Simplest and Best Solution is to use std::string instead of character arrays.
You might get answers all over which advice you to use to use dynamically allocated arrays but using std::string is the best choice, so ignore those.
EDIT:
Since somebody downvoted this. I would be very interested in knowing the reasons(provided they are technical) to do so.
You need dynamically allocated memory, and the best way to manage that is with std::vector.
std::vector<char> encryptedMessage;
encryptedMessage.resize(size_of_file);
in.get(&encryptedMessage[0], encryptedMessage.size());
#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;
}
I'm new to C++, and I'm trying to write a short C++ program that reads lines of
text from a file, with each line containing one integer key and one alphanumeric string value (no embedded whitespace). The number of lines is not known in advance, (i.e., keep reading lines until end of file is reached). The program needs to use the 'std::map' data structure to store integers and strings read from input (and to associate integers with strings). The program then needs to output string values (but not integer values) to standard output, 1 per line, sorted by integer key values (smallest to largest). So, for example, suppose I have a text file called "data.txt" which contains the following three lines:
10 dog
-50 horse
0 cat
-12 zebra
14 walrus
The output should then be:
horse
zebra
cat
dog
walrus
I've pasted below the progress I've made so far on my C++ program:
#include <fstream>
#include <iostream>
#include <map>
using namespace std;
using std::map;
int main ()
{
string name;
signed int value;
ifstream myfile ("data.txt");
while (! myfile.eof() )
{
getline(myfile,name,'\n');
myfile >> value >> name;
cout << name << endl;
}
return 0;
myfile.close();
}
Unfortunately, this produces the following incorrect output:
horse
cat
zebra
walrus
If anyone has any tips, hints, suggestions, etc. on changes and revisions
I need to make to the program to get it to work as needed, can you please
let me know?
Thanks!
See it:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string name;
int value;
ifstream myfile("text.txt", ifstream::in);
while(myfile >> value >> name)
cout << name << endl;
return 0;
}
You are having problems because you attempt to read each line twice: first with getline and then with operator>>.
You haven't actually used std::map in any regard, at all. You need to insert the integer/string pair into the map, and then iterate over it as the output. And there's no need to close() the stream.
Instead of using "! myfile.eof()" use this code it will help.
ifstream is;
string srg;
is.open(filename);
while(getline(is,srg))
{//your code
}