Tesseract OCR (C++) Cannot Evaluate Output String - c++

I am attempting to extract output string from an OpenCV Matrix window and evaluate it, but it seems to return something similar to "someString\n" rather "someString". This renders it difficult to compare knowing there are (x) amounts of white spaces.
I tried:
creating a char array that omits the white spaces (I am aware that I'm only evaluating 5 indexes)
std::string redef;
char charArr[100] = {NULL};
strcpy_s(charArr, str.c_str());
for (int i = 0; i < 5; i++)
{
if (charArr[i] != ' ')
{
redef += charArr[i];
}
}
std::cout << "analyseAction ran:" << redef << "white-space?";
but the string returns something like
analyseAction ran:redefString
white-space?
Relevant code running in main function:
api->Recognize(0);
outText = api->GetUTF8Text();
analyseAction(outText);
bellow, just take note that the else statement runs since redef doesn't equal to "long" when long is shown visually in window.
void analyseAction(std::string str)
{
std::string redef;
char charArr[100] = {NULL};
strcpy_s(charArr, str.c_str());
for (int i = 0; i < 5; i++)
{
if (charArr[i] != ' ')
{
redef += charArr[i];
}
}
std::cout << "analyseAction ran:" << redef << "white-space?";
//alot of missing code, trying to show what is relevant
if (redef == "long") //check if it has white space after long, seems like it new line's
{
//NOTE FOR FUTURE: Stop being lazy and make this a function of its own
//BUY
std::cout << "Long ran";
for (int i = 0; i < a; i++) //no comma with first line so 0 element
{
context += inData[i];
}
x = std::stoi(context);
for (int i = a+1; i < a1; i++)
{
context += inData[i];
}
y = std::stoi(context);
simClick(x,y);
//BUY CONFIRM
for (int i = a1+1; i < b; i++) //starting from pipeline??
{
context += inData[i];
}
x = std::stoi(context);
for (int i = b+1; i < b1; i++) //starting with comma? +1 to fix
{
context += inData[i];
}
y = std::stoi(context);
simClick(x, y);
}
else
{
std::cout << "long does not match";
}
}
I am confused, why does the string appear to new line? And how can I successfully evaluate the output? I am a noobie in C++ so any help will be greatly appreciated.

As for why it's returning a string and a line break, I cannot answer that. But I can provide you an alternative system to what you are trying to accomplish. Remove your first for loop in the analyseAction function and in your if statement for "long" pass in... if(charArr[0] == 'l') {//do stuff} This does have a limit if you are assessing many words that start with "l", in this case assess the first two or three letters of the word so long they aren't less than 2 or 3 letter words. PS. this was written on mobile.

Related

Why does my matrix print in 3 rows and multiple columns while i need the opposite? How can i also decrypt the message?

I am trying to encrypt a message by having it print in 3 columns and as many rows as needed. I also need help with reversing my encryption
I am having most difficulties printing my results. I am working with a Rail Fence Cipher key N which dictate number of columns. N = Number of Columns, but in my code I made it default = 3.
My Conditions are
.The plaintext is written, the sequence of each letter’s vertical position on the columns varies right and left in a repeating cycle
.The ciphertext is then read off in columns
int main()
{
int num_cols, num_spaces=0 ,f=0;
string message;
// accept the message from the user
cout<<" Enter the message to encrypt : ";
getline(cin,message);
num_cols=3;
// first we need to remove any spaces that might be there in the message
for(int i = 0 ; i<message.size(); ++i)
{
if(message[i] == ' ')
{
++num_spaces;
}
}
remove(message.begin(), message.end(),' ');
message.resize(message.size() - num_spaces);
cout<<"\n The equivalent cipher text would be : "<<endl;
vector<vector<char>> matrix(3,vector<char>(message.size(),' '));
// encrypt the message
for(int i=0,j=0; i<message.size(); i++)
{
matrix[j][i] = message[i];
if(j == 3-1)
{
f=1;
}
else if(j==0)
f=0;
if(f==0)
{
j++;
}
else j--;
}
// Printing the grid
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < message.size(); j++)
{
cout << matrix[i][j];
}
cout << endl;
}
return 0;
// end
}
So, your first problem, the correct output is easy to solve. You had just a minor typo. The encrypted text will be printed with:
// Printing the grid
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < matrix[i].size(); j++)
{
if (matrix[i][j] != ' ')
std::cout << matrix[i][j];
}
}
If you want to see the rails, then please use:
std::cout << "\n\n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < matrix[i].size(); j++)
{
std::cout << matrix[i][j];
}
std::cout << '\n';
}
So, with that the question is answered.
Deciphering is similar simple.
You create again rails and do for the length of the string the same as before. But, do not put a letter in that position, but a marker, for example a '*'.
Then go rail by rail (row by row) through your rails, and everytime, when you find a marker, the replace that marker with the next character from the encrypted text.
Then go again zigzag through your rails, and collect all characters at the corresponding positions. The result will be the drcrypted text.
I prepared a complete solution for encryption and decryption. The number of rails can be specified at the top. In my example I use 5. Please change it to 3, if you want. I made it straigthforward. For easier understanding. The code should be further optimized. E.g., there are a lot of repetions that could be put into functions.
Anyway. It is just an example:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
// Please specify the number of rails:
constexpr size_t NumberOfRails = 5u;
constexpr char EmptyRailPosition = '.';
constexpr char UsedRailPosition = '*';
// Some aliases for easier writing and understanding
using Rail = std::vector<char>;
using Rails = std::vector<Rail>;
std::string clearText{ "abcd efgh ijkl mnopqrst uv wxyz" };
int main() {
// Remove all spaces from string
clearText.erase(std::remove_if(clearText.begin(), clearText.end(), ::isspace), clearText.end());
// Create the rails for the encryption
Rails encryptedRails(NumberOfRails, Rail(clearText.length(), EmptyRailPosition));
// Now encrypt
int railIndexIncrementor{ -1 };
size_t railIndex{};
// Go thorugh all characters in the clear string
for (size_t columnIndexInClearText{}; columnIndexInClearText < clearText.length(); ++columnIndexInClearText) {
// Write character on rail
encryptedRails[railIndex][columnIndexInClearText] = clearText[columnIndexInClearText];
// If we are at the top or at the bottom of our rails, then change direction
if (0 == (columnIndexInClearText % (NumberOfRails-1)))
railIndexIncrementor = -railIndexIncrementor;
// Modify rail index. Increment or decrement. Depending on railIncrementor
railIndex = static_cast<int>(railIndex) + railIndexIncrementor;
}
// Here we will store the encrypted message
std::string encryptedMessage{};
// Show rails
std::cout << "\nRails: \n\n";
for (const Rail& rail : encryptedRails) {
for (const char c : rail) {
std::cout << c;
// Build string with encrypted message
if (c != EmptyRailPosition) encryptedMessage += c;
}
std::cout << '\n';
}
// Show encrypted message
std::cout << "\n\nEncrypted message: \n\n" << encryptedMessage << "\n\n";
// ------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------
// Decryption
// ------------------------------------------------------------------------------------
// Build empty rails
Rails decryptedRails(NumberOfRails, Rail(clearText.length(), '.'));
railIndexIncrementor = -1;
railIndex = 0;
// Go through all necessary positions in the decryption rails
for (size_t columnIndexInEncryptedText{}; columnIndexInEncryptedText < encryptedMessage.length(); ++columnIndexInEncryptedText) {
// Write makrker on rail
decryptedRails[railIndex][columnIndexInEncryptedText] = UsedRailPosition;
// If we are at the top or at the bottom of our rails, then change direction
if (0 == (columnIndexInEncryptedText % (NumberOfRails - 1)))
railIndexIncrementor = -railIndexIncrementor;
// Modify rail index. Increment or decrement. Depending on railIncrementor
railIndex = static_cast<int>(railIndex) + railIndexIncrementor;
}
// Show rails with markers
std::cout << "\n\nRails with markers: \n\n";
for (const Rail& rail : decryptedRails) {
for (const char c : rail) std::cout << c;
std::cout << '\n';
}
// Now exchange the markers with the characters of the encrypted string
size_t indexInEncryptedMessage{};
// Now, put a character from the string at positions with marker
for (Rail& rail : decryptedRails)
for (char& c : rail)
if (c == UsedRailPosition) c = encryptedMessage[indexInEncryptedMessage++];
// Show rails with replaced markers
std::cout << "\nRails with replaced markers, so decrypted rails:\n\n";
for (const Rail& rail : encryptedRails) {
for (const char c : rail) std::cout << c;
std::cout << '\n';
}
// Read back string from rails
railIndexIncrementor = -1;
railIndex = 0;
std::string decrytpedMessage{};
// Go through all necessary positions in the decryption rails
for (size_t columnIndexInEncryptedText{}; columnIndexInEncryptedText < encryptedMessage.length(); ++columnIndexInEncryptedText) {
// Read character from rail
decrytpedMessage += decryptedRails[railIndex][columnIndexInEncryptedText];
// If we are at the top or at the bottom of our rails, then change direction
if (0 == (columnIndexInEncryptedText % (NumberOfRails - 1)))
railIndexIncrementor = -railIndexIncrementor;
// Modify rail index. Increment or decrement. Depending on railIncrementor
railIndex = static_cast<int>(railIndex) + railIndexIncrementor;
}
// and, show decrypted message
std::cout << "\n\nDecypted message:\n\n" << decrytpedMessage << "\n\n";
return 0;
}

Trying to compare a randomly generated array to user filled array

I am currently working on a project to create a game of Mastermind. The user must input 3 colors and the program will compare which are the correct color and in the proper place,which are the correct color but in the wrong place, and which are the wrong color. All seems well except I'm unable to properly compare the info within the randomly generated array with the user filled array. I'm sure I'd have to use a loop to accomplish this.
-Things that I feel may be the issue:
*The information within both arrays are not being stored properly.
*conflicting types.
void gameS() {
int close, right, attempts = 0;
string choice[3],code; // holds user input
const int arrySize = 5;
srand(time(0)); //random numbers
string ranColor[arrySize] = { "R", "B", "W", "Y", "G" }; // possible color options
for (int i = 0; i < arrySize - 2; i++) //generat random colors
{
int rcolor = rand() % arrySize;
code = ranColor[rcolor];
cout << code << endl;
}
while (attempts < 10) {
cout << "You should input your color choices below. Your options are - R : Red, B : Blue, W : White, Y : Yellow, G : Green.\n" << "Please choose 3 for your " << attempts+1 << " attempt.\n" << "******************************************************\n\n";
cout << "\n\nPlease enter the color of the first peg: "; //user input to choice array spot : 1
cin >> choice[0];
cout << "\nPlease enter the color of the second peg: "; //user input to choice array spot : 2
cin >> choice[1];
cout << "\nPlease enter the color of the third peg: "; //user input to choice array spot : 3
cin >> choice[2];
attempts++; // proceeds to next turn/attempt
//checks for correct colors in correct places
for (int i = 0; i < 3; i++)
{
if (code == choice[i])
{
right++;
choice[i] = "X";
}
}
//Determin the number of right colors in the wrong place
for (int i = 0; i < 3; i++)
{
for (int y = 0; y < 3; y++) {
if (code[i] == choice[y]) {
close++;
choice[i] = "Y";
}
}
}
}
}
I receive errors for the following lines:
*'argument':conversion from tim_t to unsigned in' possible loss of data
srand(time(0));
*Using uninitialized memory 'right'
`if (code == choice[i])
{
right++;
choice[i] = "X";
}`
*Using uninitialized memory 'close'
`for (int i = 0; i < 3; i++)
{
for (int y = 0; y < 3; y++) {
if (code == choice[y])
{
close++;
choice[i] = "Y";
}
}
}
*no operator "==" matches these operands.
*Binary '==':o global operator found which takes type 'std::string'(or there is no acceptable conversion)
`for (int y = 0; y < 3; y++) {
if (code[i] == choice[y])
{
close++;
choice[i] = "Y";
}`
Any tips would be appreciated.
From what I can see there is some initialization problems.
First
int close, right, attempts = 0;
Will leave close and right empty, simply initialize them properly
int close = 0, right = 0, attempts = 0;
It looks like you want to use code as an array, but the problem is, it is not initialized as an array
string choice[3],code; // holds user input
A quick fix is
string choice[3],code[3]; // holds user input
Now, where you generate the answer, there is another syntax problem
code = ranColor[rcolor];
since you want to store the answer in the code array, an index must be specified, in this case
code[i] = ranColor[rcolor];
The final problem lies in
//checks for correct colors in correct places
for (int i = 0; i < 3; i++)
{
if (code == choice[i])
{
right++;
choice[i] = "X";
}
}
Since code is an array now, simply change the condition statement to
if (code[i] == choice[i])

Connecting n pipes linux

I was studying about pipes recently and saw this answer:
Connecting n commands with pipes in a shell?
I was intrigued about it and tried to make like a "dynamic" one, in which I introduce a string with n process and then execute the n process (i.e ls | sort). I was trying to tokenize, save in an array, but it did not work. Here is my code of my "tokenizer":
int main()
{
char str[] = "ls | sort";
int length = (sizeof(str) / sizeof(*str))-1;
int sizeCMD = 1; //If the string has zero pipe, it means it has at least 1 process
vector<char> tempV;
for (int i = 0; i < length; i++)
{
if (str[i] == '|')
{//If the string has one |, it means it has at least 2 process.
sizeCMD++;
}
tempV.push_back(str[i]);//I was going to do something else with this, but I forgot.
//cout<<i<<" "<<tempV.at(i)<<endl;
}
int j = 0;//Current position of the cmd
string comLetter = "";//it will save every single letter in certain conditions
string comLine = "";//it will save all the characters of comLetter in certain conditions
struct command cmd[sizeCMD];
const char *ls[2];
const char *sort[2];
const char *toCChar;
for (int i = 0; i < tempV.size(); i++)
{
if (tempV.at(i) != ' ' && tempV.at(i) != '|')
{//comLetter will only save characters that are not equal to blank or |.
//cout<<tempV.at(i);
comLetter += tempV.at(i);
//cout<< comLetter <<endl;
}
if (tempV.at(i) == ' ' || i == tempV.size() - 1)
{//comLine will save everything of comLetter when it detects a blank or the very end
//cout<<comLetter<<endl;
comLine = comLetter;
comLetter = "";
}
if (tempV.at(i) == '|' || i == tempV.size() - 1)
{//cmd will save everything of comLine when it detects a | or the very end.
//cout<<j<<endl;
cout << "." << comLine << "." << endl;
//cout<<i<<endl;
//cout<<toCChar<<endl;
if(comLine == "ls"){
toCChar = comLine.c_str();
ls[0] = toCChar;
ls[1] = 0; //THIS IF
cmd[0] = {ls}; //WORKS
}
if(comLine == "sort"){
sort[0] = "sort";
sort[1] = 0; //THIS IF
cmd[1] = {sort}; //WORKS
}
/*const char *ls[2];
cout<<toCChar<<endl;
ls[0] = toCChar;
ls[1] = 0;
cout<< *ls[0] << " - "<< endl;
cmd[j] = {ls};
//cout << cmd << endl;
comLine = "";*/
j++; //The position will move by one.
}
}
return fork_pipes(sizeCMD, cmd);
}
Everything made sense to me, until I found out that const char* can't be temporal as it needs the data, so I need to create 2 const char* arrays for 2 commands. That's why I've two arrays: *sort[] and *ls[], for sort and ls.
Also, I was wondering, why these lines get "ignored":
toCChar = comLine.c_str();
ls[0] = toCChar;
I'm struggling right now, if someone could please help/guide me on how to do it, I would appreciate that.

What's wrong with my dynamic programming algorithm with memoization?

*Sorry about my poor English. If there is anything that you don't understand, please tell me so that I can give you more information that 'make sence'.
**This is first time asking question in Stackoverflow. I've searched some rules for asking questions correctly here, but there should be something I missed. I welcome all feedback.
I'm currently solving algorithm problems to improve my skill, and I'm struggling with one question for three days. This question is from https://algospot.com/judge/problem/read/RESTORE , but since this page is in KOREAN, I tried to translate it in English.
Question
If there are 'k' pieces of partial strings given, calculate shortest string that includes all partial strings.
All strings consist only lowercase alphabets.
If there are more than 1 result strings that satisfy all conditions with same length, choose any string.
Input
In the first line of input, number of test case 'C'(C<=50) is given.
For each test case, number of partial string 'k'(1<=k<=15) is given in the first line, and in next k lines partial strings are given.
Length of partial string is between 1 to 40.
Output
For each testcase, print shortest string that includes all partial strings.
Sample Input
3
3
geo
oji
jing
2
world
hello
3
abrac
cadabra
dabr
Sample Output
geojing
helloworld
cadabrac
And here is my code. My code seems to work perfect with Sample Inputs, and when I made test inputs for my own and tested, everything worked fine. But when I submit this code, they say my code is 'wrong'.
Please tell me what is wrong with my code. You don't need to tell me whole fixed code, I just need sample inputs that causes error with my code. Added code description to make my code easier to understand.
Code Description
Saved all input partial strings in vector 'stringParts'.
Saved current shortest string result in global variable 'answer'.
Used 'cache' array for memoization - to skip repeated function call.
Algorithm I designed to solve this problem is divided into two function -
restore() & eraseOverlapped().
restore() function calculates shortest string that includes all partial strings in 'stringParts'.
Result of resotre() is saved in 'answer'.
For restore(), there are three parameters - 'curString', 'selected' and 'last'.
'curString' stands for currently selected and overlapped string result.
'selected' stands for currently selected elements of 'stringParts'. Used bitmask to make my algorithm concise.
'last' stands for last selected element of 'stringParts' for making 'curString'.
eraseOverlapped() function does preprocessing - it deletes elements of 'stringParts' that can be completly included to other elements before executing restore().
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#define MAX 15
using namespace std;
int k;
string answer; // save shortest result string
vector<string> stringParts;
bool cache[MAX + 1][(1 << MAX) + 1]; //[last selected string][set of selected strings in Bitmask]
void restore(string curString, int selected=0, int last=0) {
//base case 1
if (selected == (1 << k) - 1) {
if (answer.empty() || curString.length() < answer.length())
answer = curString;
return;
}
//base case 2 - memoization
bool& ret = cache[last][selected];
if (ret != false) return;
for (int next = 0; next < k; next++) {
string checkStr = stringParts[next];
if (selected & (1 << next)) continue;
if (curString.empty())
restore(checkStr, selected + (1 << next), next + 1);
else {
int check = false;
//count max overlapping area of two strings and overlap two strings.
for (int i = (checkStr.length() > curString.length() ? curString.length() : checkStr.length())
; i > 0; i--) {
if (curString.substr(curString.size()-i, i) == checkStr.substr(0, i)) {
restore(curString + checkStr.substr(i, checkStr.length()-i), selected + (1 << next), next + 1);
check = true;
break;
}
}
if (!check) { // if there aren't any overlapping area
restore(curString + checkStr, selected + (1 << next), next + 1);
}
}
}
ret = true;
}
//check if there are strings that can be completely included by other strings, and delete that string.
void eraseOverlapped() {
//arranging string vector in ascending order of string length
int vectorLen = stringParts.size();
for (int i = 0; i < vectorLen - 1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].length() < stringParts[j].length()) {
string temp = stringParts[i];
stringParts[i] = stringParts[j];
stringParts[j] = temp;
}
}
}
//deleting included strings
vector<string>::iterator iter;
for (int i = 0; i < vectorLen-1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].find(stringParts[j]) != string::npos) {
iter = stringParts.begin() + j;
stringParts.erase(iter);
j--;
vectorLen--;
}
}
}
}
int main(void) {
int C;
cin >> C; // testcase
for (int testCase = 0; testCase < C; testCase++) {
cin >> k; // number of partial strings
memset(cache, false, sizeof(cache)); // initializing cache to false
string inputStr;
for (int i = 0; i < k; i++) {
cin >> inputStr;
stringParts.push_back(inputStr);
}
eraseOverlapped();
k = stringParts.size();
restore("");
cout << answer << endl;
answer.clear();
stringParts.clear();
}
}
After determining which string-parts can be removed from the list since they are contained in other string-parts, one way to model this problem might be as the "taxicab ripoff problem" problem (or Max TSP), where each potential length reduction by overlap is given a positive weight. Considering that the input size in the question is very small, it seems likely that they expect a near brute-force solution, with possibly some heuristic and backtracking or other form of memoization.
Thanks Everyone who tried to help me solve this problem. I actually solved this problem with few changes on my previous algorithm. These are main changes.
In my previous algorithm I saved result of restore() in global variable 'answer' since restore() didn't return anything, but in new algorithm since restore() returns mid-process answer string I no longer need to use 'answer'.
Used string type cache instead of bool type cache. I found out using bool cache for memoization in this algorithm was useless.
Deleted 'curString' parameter from restore(). Since what we only need during recursive call is one previously selected partial string, 'last' can replace role of 'curString'.
CODE
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#define MAX 15
using namespace std;
int k;
vector<string> stringParts;
string cache[MAX + 1][(1 << MAX) + 1];
string restore(int selected = 0, int last = -1) {
if (selected == (1 << k) - 1) {
return stringParts[last];
}
if (last == -1) {
string ret = "";
for (int next = 0; next < k; next++) {
string resultStr = restore(selected + (1 << next), next);
if (ret.empty() || ret.length() > resultStr.length())
ret = resultStr;
}
return ret;
}
string& ret = cache[last][selected];
if (!ret.empty()) {
cout << "cache used in [" << last << "][" << selected << "]" << endl;
return ret;
}
string curString = stringParts[last];
for (int next = 0; next < k; next++) {
if (selected & (1 << next)) continue;
string checkStr = restore(selected + (1 << next), next);
int check = false;
string resultStr;
for (int i = (checkStr.length() > curString.length() ? curString.length() : checkStr.length())
; i > 0; i--) {
if (curString.substr(curString.size() - i, i) == checkStr.substr(0, i)) {
resultStr = curString + checkStr.substr(i, checkStr.length() - i);
check = true;
break;
}
}
if (!check)
resultStr = curString + checkStr;
if (ret.empty() || ret.length() > resultStr.length())
ret = resultStr;
}
return ret;
}
void EraseOverlapped() {
int vectorLen = stringParts.size();
for (int i = 0; i < vectorLen - 1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].length() < stringParts[j].length()) {
string temp = stringParts[i];
stringParts[i] = stringParts[j];
stringParts[j] = temp;
}
}
}
vector<string>::iterator iter;
for (int i = 0; i < vectorLen - 1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].find(stringParts[j]) != string::npos) {
iter = stringParts.begin() + j;
stringParts.erase(iter);
j--;
vectorLen--;
}
}
}
}
int main(void) {
int C;
cin >> C;
for (int testCase = 0; testCase < C; testCase++) {
cin >> k;
for (int i = 0; i < MAX + 1; i++) {
for (int j = 0; j < (1 << MAX) + 1; j++)
cache[i][j] = "";
}
string inputStr;
for (int i = 0; i < k; i++) {
cin >> inputStr;
stringParts.push_back(inputStr);
}
EraseOverlapped();
k = stringParts.size();
string resultStr = restore();
cout << resultStr << endl;
stringParts.clear();
}
}
This algorithm is much slower than the 'ideal' algorithm that the book I'm studying suggests, but it was fast enough to pass this question's time limit.

how to print out x amount of results per line

For this code I created that outputs the ASCII characters corresponding to ints, I need to print out 16 ASCIIs per line. How would I go about doing so? I'm not sure how to approach these? Do I create another for loop inside?
int main()
{
int x = 0;
for (int i = 0; i <= 127; i++)
{
int x = i;
char y = (char) x;
cout << y;
}
return 0;
}
Or should I put the cout outside with 16 separate lines? I am trying to print 17 ASCIIs starting from 1 in a row.
Use another variable that counts up along with i. When it reaches 16, reset it and print a new line. Repeat until the loop terminates.
i.e.(I may be off by one here, I didn't think about it too deeply)
for (int i=0, j=1; i<=127; i++,j++)
{
int x = i;
char y = (char) x;
cout << y;
if (j == 16) {
j = 0;
cout << '\n';
}
}
Alternatively, you could just check if (i % 16 == 0)
You don't need another variable to track it. i is already an int.
so if i modulo 16 equals 0 then print a newline
else print (char)i
EDIT:
Note, using variables like i is ok for simple iteration but its always good practice to name them better.
So think about how changing i to ascii in your program improves the readability. It instantly makes it even more clear what is it that you are trying to do here.
int main()
{
int charsThisLine =0;
for (int currentChar=0; currentChar<128; currentChar++)
{
if(charsThisLine==16)
{
cout<<endl;
charsThisLine = 0;
}
else
{
cout<<(char)currentChar;
charsThisLine++;
}
}
}
How about:
#include <iostream>
int main()
{
for(int i = 0, j = 0; i < 128; ++i, ++j)
{
if(j == 16)
{
j = 0;
std::cout << std::endl;
}
std::cout << static_cast<char>(i);
}
return 0;
}
Every iteration, j increases by 1; after 16 iterations, j is reset to 0, and a newline is printed.
Alternatively, as #Sujoy points out, you could use:
if((i % 16) == 0)
std::cout << std::endl;
But this introduces the problem of printing an extra newline character at the beginning of the output.
Yes, you need a second loop inside the first. (I misunderstood what is being requested.)
You also need to clean up the code. The first x is unused; the second x isn't needed since you could perfectly well use char y = (char)i; (and the cast is optional). You should normally use a loop for (int i = 0; i < 128; i++) with a < condition rather than <=.
You will also need to generate a newline somewhere (cout << endl; or cout << '\n';). Will you be needing to deal with control characters such as '\n' and '\f'?
Finally, I'm not sure that 'asciis' is a term I've seen before; the normal term would be 'ASCII characters'.