C语言 输入字符串,将字符串中的数字存入整型数组中

C语言 输入字符串,将字符串中的数字存入整型数组中,第1张

#include<stdioh>

#include<stringh>

int main()

  char str[20];

  int i,j;

  int b[20];

  printf("这里输入字符串\n");

  scanf("%s",str);

  for(i=0,j=0;i<strlen(str);i++,j++)

      {

          if((str[i]>'0')&&(str[i]<'9'))

          {

              b[j]=(int)str[i]-48;

              printf("%d",b[j]);

          }

          else j--;

      }

  return 0;

}

已经运行成功,希望能帮助你,欢迎追问

方法一:使用二维字符数组,示例:
#include<stdioh>
#include<stdlibh>
int main(int argc, char argv[])
{
char c[][5] = {"abc","haha","no"};
for (int i=0; i<3; i++)
{
printf("%s\n",c[i]);
}
return 0;
}
方法二:使用 string 数组,示例:
#include<stdioh>
#include<stdlibh>
#include <stringh>
int main(int argc, char argv[])
{
string s[] = {"abc","haha","no"};
for (int i=0; i<3; i++)
{
printf("%s\n",s[i]c_str());
}
return 0;
}

一串数字,是一个整数吗?还是一个字符串?如果是字符串的话,本身就是一个数组。整数的话就把每位取出来赋值。

#include "stdafxh"

#include <iostream>

using namespace std;

#define N 20

int main()

{

int num,a[N],n=0;

char s[N];

cout << "请输入一串数字(数字处理):" << endl;

cin >> num;

int temp = num;

while (temp)

{

n++;

temp /= 10;

}

for (int i = n - 1; i >= 0; i--)

{

a[i]=num%10;

num /= 10;

}

for (int i = 0; i < n; i++)

cout << a[i] << " ";

cout << "\n请输入一串数字(字符串处理):" << endl;

cin >> s;

for (int i = 0;s[i]!='\0'; i++)

cout << s[i] << " ";

cout << endl;

system("pause");

  return 0;

}

方法:

先拆分,然后把拆分的字符串存到数据组中即可,代码参考

public class STest
{
 public static void main(String[] args)
 {
  String t="abc,edf,xyz";
  String[] chrstr=tsplit(",");
  for(int i=0;i<chrstrlength;i++)
  {
       Systemoutprintln(chrstr[i]);
  }
 }
}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/13337403.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-07-17
下一篇 2023-07-17

发表评论

登录后才能评论

评论列表(0条)

保存