scanf from console and fscanf from file - printf

I got some problems about scanf from console,
I wrote some codes about it and found that it could not read all the input and automatically close after typing first character.
int readLetterGridFromConsole(char letterGrid[MAX_GRID][MAX_GRID]) {
int row, col;
int gridSize;
printf("Enter the size of the letter grid:\n");
scanf("%d", &gridSize);
if(gridSize < 2 || gridSize > MAX_GRID) {
printf("DEBUG: gridSize is %d but not between 2 and %d\n", gridSize, MAX_GRID);
printf("Program terminates.\n");
exit(1);
} else {
printf("Enter the letter grid:\n");
for(row = 0; row < gridSize; row++) {
for(col = 0; col < gridSize; col++) {
scanf(" %c", &letterGrid[row][col]);
}
}
return gridSize;
}
}
I would like to store these input in the 2D array ( letterGrid )
how could I solve this problem? Thanks for help!

But it works for me.
I define a 2-D array char x[MAX_GRID][MAX_GRID]; then pass it to function, then scan input then store them in the x matrix.
Code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_GRID 2
int readLetterGridFromConsole(char letterGrid[MAX_GRID][MAX_GRID]) {
int row, col;
int gridSize;
printf("Enter the size of the letter grid:\n");
scanf("%d", &gridSize);
if(gridSize < 2 || gridSize > MAX_GRID) {
printf("DEBUG: gridSize is %d but not between 2 and %d\n", gridSize, MAX_GRID);
printf("Program terminates.\n");
exit(1);
} else {
printf("Enter the letter grid:\n");
for(row = 0; row < gridSize; row++) {
for(col = 0; col < gridSize; col++) {
scanf(" %c", &letterGrid[row][col]);
}
}
//return gridSize;
}
/*
printf("Lettr grid\n\n");
for(row = 0; row < gridSize; row++) {
for(col = 0; col < gridSize; col++) {
printf("%c", letterGrid[row][col]);
}
}
*/
}
int main()
{
char x[MAX_GRID][MAX_GRID];//={{1,2},{3,4}};
readLetterGridFromConsole(x);
printf("after function\n\n\n");
for(int row = 0; row < MAX_GRID; row++) {
for(int col = 0; col < MAX_GRID; col++) {
printf("%c", x[row][col]);
}
}
return 0;
}
Compile and Run
gcc -Wall -Wextra -pedantic-errors code.c -o code
Output
Enter the size of the letter grid:
2
Enter the letter grid:
a
b
c
d
after function
abcd
Consider as array in c pass by reference it can hold values even outside of function readLetterGridFromConsole(x);

Related

BIG WEIRD ANSWER in a MATRIX multiplication program

this is a program to multiply 2 matrixes which comes in maths, but dont know why, am getting answers like "-1282230" or some weird numbers. I would like to know what is causing it and how could i fix it? THANK YOU!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
int m[3][3],m2[3][3],i,je,k,ans[3][3],sum;
// taking inputs from the user for matrix1
printf("Enter the numbers for first matrix");
je=0;
for(i=0;i<3;i++){
printf(" for row %d\n",i+1);
for(je=0;je<3;je++){
scanf("%d",&m[i][je]);
}
}
// taking inputs from the user for matrix2
printf("Enter the numbers for second matrix");
je=0;
for(i=0;i<3;i++){
printf(" for row = %d\n",i+1);
for(je=0;je<3;je++){
scanf("%d",&m2[i][je]);
}
}
// multiplication OR MATRIX CMS HERE;
sum = 0;
for(k=0;k<9;k++){
for(i=0;i<3;i++){
for(je=0;je<3;je++){
sum = m[k][je] * m2[je][i];
ans[i][je] = sum;
}
}
k++;
}
// it ENDS;
puts("ANSWER IS:: \n");
// Displaying answer, matrix;
for(i=0;i<3;i++){
for(je=0;je<3;je++){
printf("%d\t",ans[i][je]);
}
printf("\n");
}
return 0;
}
Here's a working solution. One of the problem with your code is that you aren't setting the sum to 0 after each multiplication.
#include <stdio.h>
int main() {
int m, n, p, q, c, d, k, sum = 0; int first[10][10], second[10][10], multiply[10][10];
printf("Enter number of rows and columns of first matrix\n"); scanf("%d%d", &m, &n); printf("Enter elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter number of rows and columns of second matrix\n"); scanf("%d%d", &p, &q);
if (n != p)
printf("The matrices can't be multiplied with each other.\n"); else {
printf("Enter elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of the matrices:\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0; }

compare images using systemC

I wrote in this forum asking for help to solve this problem that took ame a lot of my time,i write my first program using systemC, I will expain my aim as much as I can , I stored 2 matrix of pixel value of image in two different text files, I write a systemC code that load two matrix and apply somme of absolute difference, if number of different superior of a Threshold the code displays message (motion).
My code composed of two modules, the first module check if there a number stored in a text file, if yes this Module will automates the other module to load the two matrix and compare them, I really need this code for my project graduation any help or suggestion.
#include "systemC.h"
#include "string.h"
#include "stdio.h"
#include"stdlib.h"
#include <time.h>
#include <math.h> /* fabs */
#include <fstream>
#include <iostream>
#include <fstream>
using namespace std;
#define _CRT_SECURE_NO_WARNINGS
_CRT_SECURE_NO_WARNINGS
double elapsed;
int H = 0;
int D = 0;
int a, b;
int in = false;
int L = 0;
char *mode1 = "r";
char *mode2 = "w";
int i, j, k;
int rows1, cols1, rows2, cols2;
bool fileFound = false;
FILE *SwitchContext;
FILE *image1;
FILE *image2;
FILE *image3;
int sum = 0;
clock_t start = clock();
SC_MODULE(synchronization)
{
sc_in<bool>sig ;
SC_CTOR(synchronization)
{
SC_METHOD(synchroprocess)
}
void synchroprocess()
{
cout << "\n Running Automation";
SwitchContext = fopen("F:/SWITCH CONTEXT.txt", mode2);
fscanf(SwitchContext, "%d", &L);
while (L != 0)
{
cout << "waiting...";
}
sig == true;
}
};
SC_MODULE(imageProcess)
{
sc_in<bool>sig;
SC_CTOR(imageProcess)
{
SC_METHOD(MotionDetector)
sensitive(sig);
}
void MotionDetector()
{
image3 = fopen("F:/image3.txt", mode2);
do
{
char *mode1 = "r";
char *mode2 = "w";
image1 = fopen("F:/image1.txt", mode1);
if (!image1)
{
printf("File Not Found!!\n");
fileFound = true;
}
else
fileFound = false;
}
while (fileFound);
do
{
image2 = fopen("F:/image2.txt", mode1);
if (!image2)
{
printf("File Not Found!!\n");
fileFound = true;
}
else
fileFound = false;
}
while (fileFound);
rows1 = rows2 = 384;
cols1 = cols2 = 512;
int **mat1 = (int **)malloc(rows1 * sizeof(int*));
for (i = 0; i < rows1; i++)
mat1[i] = (int *)malloc(cols1 * sizeof(int));
i = 0;
int **mat2 = (int **)malloc(rows2 * sizeof(int*));
for (i = 0; i < rows2; i++)
mat2[i] = (int *)malloc(cols2 * sizeof(int));
i = 0;
while (!feof(image1))
{
for (i = 0; i < rows1; i++)
{
for (j = 0; j < cols1; j++)
fscanf(image1, "%d%", &mat1[i][j]);
}
}
i = 0;
j = 0;
while (!feof(image2))
{
for (i = 0; i < rows2; i++)
{
for (j = 0; j < cols2; j++)
fscanf(image2, "%d%", &mat2[i][j]);
}
}
i = 0;
j = 0;
printf("\n\n");
for (i = 0; i < rows1; i++)
{
for (j = 0; j < cols1; j++) {
a = abs(mat1[i][j] = mat2[i][j]);
b = b + a;
}
}
i = j = 0;
D = b / 196608;
if (D > 0.9)
{
printf("%d,&K");
printf("MOTION...DETECTED");
getchar();
sc_pause;
for (i = 0; i < rows1; i++) {
for (j = 0; j < cols1; j++)
{
fprintf(image3, "%d ", mat2[i][j]);
}
fprintf(image3, "\n");
}
printf("\n Image Saved....");
std::ofstream mon_fichier("F:\toto.txt");
mon_fichier << elapsed << '\n';
}
fclose(image1);
fclose(image2);
fclose(image3);
clock_t end = clock();
elapsed = ((double)end - start) / CLOCKS_PER_SEC;
printf("time is %f", elapsed);
}
};
int sc_main(int argc, char* argv[])
{
imageProcess master("EE2");
master.MotionDetector();
sc_start();
return(0);
}
What you did is basically wrong.
You copy pasted code to SC_MODULE, this code is simple C code
(Do not mix C and C++ files)
This is not how you use clock
What you should do:
You need to check if your algorithm works, for this you do not need SystemC at all
Then you can replace data types with HW one and check if it still works
Then you have to find which data interface is used in HW and how to use this interface
Then you have to tweak your alg. to work with this interface (There you can use SC_MODULE, sc ports etc...)
Also take look at SC_CTHREAD, you will need it.
Without any informations about target platform I can not provide any other help.

TLE in Foe Pairs (Educational Codeforces Round 10)

On implementing O(N+M) complexity code for Foe Pairs problem
http://codeforces.com/contest/652/problem/C, I am getting TLE in Test Case 12.
Constraint : (1 ≤ N, M ≤ 3·105)
I am not getting, why for this constraint O(N+M) is getting TLE.
Here, is the code
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
std::vector<int> v(n+1);
for (int i = 0; i < n; ++i)
{
int x;
cin>>x;
v[x] = i;
}
std::vector<int> dp(n,0);
for (int i = 0; i < m; ++i)
{
int a,b;
cin>>a>>b;
if(v[a]>v[b])
swap(a,b);
dp[v[b]] = max(dp[v[b]], v[a]+1);
}
for (int i = 1; i < n; ++i)
{
dp[i] = max(dp[i], dp[i-1]);
}
long long s = 0;
for (int i = 0; i < n; ++i)
{
s+=(i+1-dp[i]);
}
cout<<s;
}
Is there anything, I am missing?
I changed all cin to scanf, it passed all test cases : http://codeforces.com/contest/652/submission/17014495
#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n,m;
scanf("%d%d", &n, &m);
//cin>>n>>m;
std::vector<int> v(n+1);
for (int i = 0; i < n; ++i)
{
int x;
//cin>>x;
scanf("%d", &x);
v[x] = i;
}
std::vector<int> dp(n,0);
for (int i = 0; i < m; ++i)
{
int a,b;
//cin>>a>>b;
scanf("%d%d", &a, &b);
if(v[a]>v[b])
swap(a,b);
dp[v[b]] = max(dp[v[b]], v[a]+1);
}
for (int i = 1; i < n; ++i)
{
dp[i] = max(dp[i], dp[i-1]);
}
long long s = 0;
for (int i = 0; i < n; ++i)
{
s+=(i+1-dp[i]);
}
cout<<s;
return 0;
}
You should always try to use scanf when the amount of input is large as it is faster.
You can read more about scanf being faster here : Using scanf() in C++ programs is faster than using cin?

Searching a word in a 2d array in c programming

I am trying to set up a program that when you type /s then a movie title (ex. /s Green Mile it searches for that movie title in the movies array but my strstr function is not working. Also /a adds movie /r shows all movies in database and /q quits program.
#include <stdio.h>
#include <string.h>
main() {
char movies[1000][64];
int i;
int j = 1;
int k = 0;
int counter = 0;
char buffer[64];
char buffer2[64];
int len;
do {
printf("Enter command for movie database:\n");
fgets(buffer, 64, stdin);
if (buffer[1] == 'a') {
len = strlen(buffer);
if (buffer[len - 1] == '\n')
buffer[len - 1] = '\0';
for(i=3; i<sizeof(buffer); i++) {
movies[counter][k] = buffer[i];
k++;
}
printf("You have chosen to enter a movie in the database.\n");
printf("The movie added to the database is: %s\n", &movies[counter][0]);
counter++;
k = 0;
}
if (buffer[1] == 'q') {
printf("You have chosen to quit.\n");
printf("Goodbye.\n");
}
if (buffer[1] == 's') {
for(i=2; i<sizeof(buffer); i++) {
buffer2[k] = buffer[i];
k++;
}
for (i = 0; i < counter; i++) {
if (strstr(movies[i], buffer2) != NULL) {
printf("Found %s in position %d,%s\n", buffer2, i + 1, movies[i]);
printf("Index of Movie is %d.\n", i + 1);
}
}
k = 0;
}
if (buffer[1] == 'r') {
printf("You have choosen to report movies in database\n");
printf("These are the movies you have watched:\n");
for( i = 0; i < counter; i++ ) {
printf("%d: %s\n", j, &movies[i][0]);
j++;
}
printf("\n");
j = 1;
}
} while (buffer[1] != 'q');
}
Revised code.
#include <stdio.h>
#include <string.h>
main() {
char movies[1000][64];
int counter = 0;
char buffer[64];
char * movieTitle = &buffer[3];
while(true) {
printf("Enter command for movie database:\n");
fgets(buffer, 64, stdin);
//replace terminator every time
int len = strlen(buffer);
if (buffer[len - 1] == '\n')
buffer[len - 1] = '\0';
if(strstr(buffer, "/a") && counter < 1000) {
strcpy(movies[counter], movieTitle);
printf("You have chosen to enter a movie in the database.\n");
printf("The movie added to the database is: %s\n", &movies[counter][0]);
counter++;
}
else if (strstr(buffer, "/s")) {
for (int i = 0; i < counter; i++) {
if (strcmp(movies[i], movieTitle) == 0) {
printf("Found %s in position %d,%s\n", movieTitle, i + 1, movies[i]);
printf("Index of Movie is %d.\n", i + 1);
}
}
}
else if (strstr(buffer, "/r")) {
printf("You have choosen to report movies in database\n");
printf("These are the movies you have watched:\n");
for( i = 0; i < counter; i++ ) {
printf("%d: %s\n", i + 1, &movies[i][0]);
}
printf("\n");
}
else if (strstr(buffer, "/q")) {
printf("You have chosen to quit.\n");
printf("Goodbye.\n");
break;
}
else {
printf("unrecognized command");
}
}
}

Factorial in bignum library

Ive tried to create my own implementation of a bignum library
I cant seem to get the factorial to work. If I ask it to solve 4!, it gives out 96. It multiplies 4 twice. similarly, 5! is 600, not 120. I haven't implemented division, so I cant/dont want to divide the answer by the number
//bignum project
#include <iostream>
using namespace std;
class bignum
{
public:
int number[100];
int dpos;
int operator/ (bignum);
bignum operator- (bignum);
bignum operator* (bignum);
bignum operator+ (bignum);
bignum operator= (string);
void output()
{
int begin=0;
for(int i=0; i<=99; i++)
{
if(number[i]!=0 || begin==1)
{
cout<<number[i];
begin=1;
}
}
}
};
bool num_is_zero(bignum k)
{
for(int a=0; a<=99; a++)
{
if(k.number[a]!=0)
{
return false;
}
}
return true;
}
bignum factorial(bignum a)
{
bignum j;
bignum fact;
fact="1";
while(!num_is_zero(a))
{
j="1";
fact=fact*a;
a=a-j;
}
return fact;
}
bignum bignum::operator= (string k)
{
int l;
l=k.length()-1;
for(int h=0; h<=99; h++)
{
number[h]=0;
}
for(int a=99; a>=0 && l>=0; a--)
{
number[a]=k[l]-'0';
l--;
}
}
bignum bignum::operator+ (bignum b)
{
bignum a;
int carry=0;
for(int k=0; k<=99; k++)
{
a.number[k]=0;
}
for(int i=99; i>=0; i--)
{
a.number[i]= number[i]+b.number[i]+a.number[i];
if(a.number[i]>9)
{
carry=(a.number[i]/10);
a.number[i-1]+=carry;
a.number[i]=(a.number[i]%10);
}
}
return (a);
}
bignum bignum::operator- (bignum c)
{
bignum a;
int sign=0;
for(int k=0; k<=99; k++)
{
a.number[k]=0;
}
for(int i=99; i>=0; i--)
{
if(number[i]<c.number[i])
{
number[i]+=10;
if(i!=0)
number[i-1]--;
}
a.number[i]=number[i]-c.number[i];
}
return (a);
}
bignum bignum::operator* (bignum b)
{
bignum ans;
int ans_grid[100][100],x,lines=0,carry,sum[100];
for(int a=0; a<=99; a++)
{
for(int b=0; b<=99; b++)
{
ans_grid[a][b]=0;
}
}
for(int i=99; i>=0; i--)
{
for(int j=i,x=99; j>=0; j--,x--)
{
ans_grid[lines][j]=(number[i]*b.number[x]);
}
lines++;
}
//------------------------------------------------Carry Forward and assign to ans------------------------------------------------//
for(int j=99; j>=0; j--)
{
for(int i=99; i>=0; i--)
{
if(ans_grid[j][i]>9 && i!=0)
{
carry=(ans_grid[j][i]/10);
ans_grid[j][i-1]+=carry;
ans_grid[j][i]%=10;
}
}
}
for(int col=99; col>=0; col--)
{
for(int row=99; row>=0; row--)
{
sum[col]+=ans_grid[row][col];
}
}
for(int i=99; i>=0; i--)
{
if(sum[i]>9 && i!=0)
{
carry=(sum[i]/10);
sum[i-1]+=carry;
sum[i]%=10;
}
}
for(int l=0; l<=99; l++)
ans.number[l]=sum[l];
//-------------------------------------------------------------------------------------------------------------------------------//
return (ans);
}
I think your problem is that sum is uninitialized in your operator*. I'm reluctant to give a partial answer, since I took the code and fiddled with it a bit, so here's my version which appears to work (and also prints "0" correctly):
Update: I couldn't resist making several structural improvements. I didn't touch your multiplication routine, so you should still be able to extract the bugfix even if you don't care for the rest.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class bignum
{
public:
int number[100];
bignum() { std::fill(number, number + 100, 0); }
bignum(const bignum & other) { std::copy(other.number, other.number + 100, number); }
bignum(const std::string &);
bignum & operator-=(const bignum &);
inline bignum operator-(const bignum & c) const { return bignum(*this) -= c; }
bignum operator*(const bignum &) const;
inline bignum & operator= (const std::string & k) { return *this = bignum(k); }
inline operator bool() const
{
for (size_t a = 0; a < 100; ++a)
if (number[a] != 0) return true;
return false;
}
};
std::ostream & operator<<(std::ostream & o, const bignum & b)
{
bool begun = false;
for (size_t i = 0; i < 100; ++i)
{
if (begun || b.number[i] != 0)
{
cout << b.number[i];
begun = true;
}
}
if (!begun) o << "0";
return o;
}
bignum::bignum(const std::string & k)
{
std::fill(number, number + 100, 0);
for(size_t h = 0; h < std::min(k.length(), 100U); ++h)
number[99 - h] = k[k.length() - 1 - h] - '0';
}
bignum & bignum::operator-=(const bignum & c)
{
for (int i = 99; i >= 0; --i)
{
if (number[i] < c.number[i])
{
number[i] += 10;
if (i != 0) --number[i-1];
}
number[i] -= c.number[i];
}
return *this;
}
bignum bignum::operator*(const bignum & b) const
{
bignum ans;
int ans_grid[100][100], lines = 0, carry, sum[100];
std::fill(sum, sum + 100, 0);
for (size_t i = 0; i < 100; ++i) std::fill(ans_grid[i], ans_grid[i] + 100, 0);
for(int i=99; i>=0; i--)
{
for(int j=i,x=99; j>=0; j--,x--)
{
ans_grid[lines][j]=(number[i]*b.number[x]);
}
lines++;
}
//------------------------------------------------Carry Forward and assign to ans------------------------------------------------//
for(int j=99; j>=0; j--)
{
for(int i=99; i>=0; i--)
{
if(ans_grid[j][i]>9 && i!=0)
{
carry=(ans_grid[j][i]/10);
ans_grid[j][i-1]+=carry;
ans_grid[j][i]%=10;
}
}
}
for(int col=99; col>=0; col--)
{
for(int row=99; row>=0; row--)
{
sum[col]+=ans_grid[row][col];
}
}
for(int i=99; i>=0; i--)
{
if(sum[i]>9 && i!=0)
{
carry=(sum[i]/10);
sum[i-1]+=carry;
sum[i]%=10;
}
}
for(int l=0; l<=99; l++)
ans.number[l]=sum[l];
//-------------------------------------------------------------------------------------------------------------------------------//
return (ans);
}
bignum factorial(bignum a)
{
bignum j; j = "1";
bignum fact; fact="1";
while(a)
{
fact = fact * a;
a = a-j;
}
return fact;
}
int main(int argc, char * argv[])
{
if (argc < 2) return 0;
bignum a;
a = std::string(argv[1]);
bignum b = factorial(a);
cout << a << std::endl << b << std::endl;
}
The string assignment is still broken for strings with more than one digit, but that wasn't your question I suppose...