佳礼资讯网

 找回密码
 注册

ADVERTISEMENT

查看: 1203|回复: 8

【求助】如何把string变成int在C++(急)

[复制链接]
发表于 13-9-2009 01:54 PM | 显示全部楼层 |阅读模式
我现在的情况是我用ifstream来读取一个txt flie的资料,然后我把他存在一个array里,因为那个file里有文字跟数字,所以我的array type是用string……
可是我要用里面的数字资料来算东西……所以要把string convert 去int……
但是不知道为什么我没有办法用atoi 来convert string 去int……
是不是我哪里弄错了??
有哪个高人可以教教我!!
回复

使用道具 举报


ADVERTISEMENT

发表于 13-9-2009 02:26 PM | 显示全部楼层
/* atoi example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i;
  char szInput [256];
  printf ("Enter a number: ");
  fgets ( szInput, 256, stdin );
  i = atoi (szInput);
  printf ("The value entered is %d. The double is %d.\n",i,i*2);
  return 0;
}
回复

使用道具 举报

发表于 13-9-2009 06:29 PM | 显示全部楼层

回复 1# 苏纳怪 的帖子

string str = xxxxxx;
int num = atoi(str.c_str());
回复

使用道具 举报

发表于 13-9-2009 06:38 PM | 显示全部楼层
回复

使用道具 举报

 楼主| 发表于 13-9-2009 11:04 PM | 显示全部楼层
ok了,谢谢大家的帮忙!!
回复

使用道具 举报

 楼主| 发表于 13-9-2009 11:19 PM | 显示全部楼层
我还有个问题想问大家,如果我的variable的type是int,要是打char下去的话,program会出error,有没有办法可以解决……
比如说当你打进不是int的东西时,他会重新让你打过??
回复

使用道具 举报

Follow Us
发表于 14-9-2009 09:49 AM | 显示全部楼层
回复

使用道具 举报

 楼主| 发表于 14-9-2009 07:34 PM | 显示全部楼层
想问要怎样用getline??
因为当我用loop里有用getline时不知道为什么当loop超过2次时,第一个getline就没有办法打input
eg code:
char name1[99],passport [99];
    cin>>number;
            for(int i=1;i<=number;i++)
    {     
            cout<<"NAME : ";
            cin.getline(name1,99);
            cout<<" PASSPORT NUMBER : ";
            cin.getline(passport,99);
            cout<<"NAME : "<<name1<<endl;
            cout<<"  PASSPORT NUMBER : "<<passport<<endl;
    }
回复

使用道具 举报


ADVERTISEMENT

发表于 16-9-2009 02:30 PM | 显示全部楼层
cin.ignore();

因为  \n  跑进 getline(name) 里了
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

 

ADVERTISEMENT



ADVERTISEMENT



ADVERTISEMENT

ADVERTISEMENT


版权所有 © 1996-2023 Cari Internet Sdn Bhd (483575-W)|IPSERVERONE 提供云主机|广告刊登|关于我们|私隐权|免控|投诉|联络|脸书|佳礼资讯网

GMT+8, 26-5-2024 10:13 AM , Processed in 0.061933 second(s), 24 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表